Base: codex-main originale (prima del fork aKode)
This commit is contained in:
263
codex-rs/mermaid/src/draw.rs
Normal file
263
codex-rs/mermaid/src/draw.rs
Normal file
@@ -0,0 +1,263 @@
|
||||
//! Orthogonal routes with unique lanes and endpoint positions, in all four directions.
|
||||
//!
|
||||
//! Routes never share segments. Crossings are explicitly marked; labels occupy reserved gutters.
|
||||
|
||||
use super::Direction;
|
||||
use super::Graph;
|
||||
use super::RenderError;
|
||||
use super::Role;
|
||||
use super::Shape;
|
||||
use super::Span;
|
||||
use super::output::Cell;
|
||||
use super::output::finish;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>, RenderError> {
|
||||
let horizontal = matches!(graph.direction, Direction::Right | Direction::Left);
|
||||
let labels = graph
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let mut lines = node
|
||||
.label
|
||||
.split('\n')
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
if node.shape == Shape::Decision {
|
||||
lines[0].insert_str(0, "◇ ");
|
||||
}
|
||||
if !node.members.is_empty() {
|
||||
lines.push("─".repeat(node.label.width()));
|
||||
lines.extend(node.members.iter().cloned());
|
||||
}
|
||||
lines
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let label_width = graph
|
||||
.edges
|
||||
.iter()
|
||||
.flat_map(|edge| [&edge.label, &edge.target_label])
|
||||
.map(|label| label.width())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let box_cross = if horizontal {
|
||||
labels.iter().map(Vec::len).max().unwrap_or(0) + 2
|
||||
} else {
|
||||
labels
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|label| label.width())
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
+ 4
|
||||
};
|
||||
let mut counts = vec![0; graph.nodes.len()];
|
||||
let mut ports = Vec::new();
|
||||
for edge in &graph.edges {
|
||||
let source = counts[edge.from];
|
||||
counts[edge.from] += 1;
|
||||
let target = counts[edge.to];
|
||||
counts[edge.to] += 1;
|
||||
ports.push((source, target));
|
||||
}
|
||||
let stride = if horizontal { label_width + 2 } else { 1 };
|
||||
let sizes = labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, lines)| {
|
||||
if horizontal {
|
||||
(lines.iter().map(|line| line.width()).max().unwrap_or(0) + 4)
|
||||
.max(counts[i] * stride + 2)
|
||||
} else {
|
||||
lines.len() + counts[i] + 2
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut starts = vec![0; graph.nodes.len()];
|
||||
let mut along = 0;
|
||||
for i in 0..graph.nodes.len() {
|
||||
let i = if matches!(graph.direction, Direction::Up | Direction::Left) {
|
||||
graph.nodes.len() - 1 - i
|
||||
} else {
|
||||
i
|
||||
};
|
||||
starts[i] = along;
|
||||
along += sizes[i] + 2;
|
||||
}
|
||||
let first_lane = box_cross + if horizontal { 4 } else { label_width + 5 };
|
||||
let across = if graph.edges.is_empty() {
|
||||
box_cross
|
||||
} else {
|
||||
first_lane + graph.edges.len() * 2 - 1
|
||||
};
|
||||
let (width, height) = if horizontal {
|
||||
(along - 2, across)
|
||||
} else {
|
||||
(across, along - 2)
|
||||
};
|
||||
if width > max_width {
|
||||
return Err(RenderError::TooWide);
|
||||
}
|
||||
if width * height > super::MAX_CELLS {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
let mut canvas = Canvas {
|
||||
cells: vec![vec![Cell::edge(' '); width]; height],
|
||||
horizontal,
|
||||
};
|
||||
for (i, lines) in labels.iter().enumerate() {
|
||||
let start = starts[i];
|
||||
let end = start + sizes[i] - 1;
|
||||
let [top_left, top_right, bottom_left, bottom_right] = match graph.nodes[i].shape {
|
||||
Shape::Stadium => ['╭', '╮', '╰', '╯'],
|
||||
Shape::Rectangle | Shape::Decision => ['┌', '┐', '└', '┘'],
|
||||
};
|
||||
canvas.set(/*across*/ 0, start, Cell::node(top_left));
|
||||
canvas.set(box_cross - 1, start, Cell::node(top_right));
|
||||
canvas.set(/*across*/ 0, end, Cell::node(bottom_left));
|
||||
canvas.set(box_cross - 1, end, Cell::node(bottom_right));
|
||||
for x in 1..box_cross - 1 {
|
||||
canvas.set(x, start, Cell::node('─'));
|
||||
canvas.set(x, end, Cell::node('─'));
|
||||
}
|
||||
for y in start + 1..end {
|
||||
canvas.set(/*across*/ 0, y, Cell::node('│'));
|
||||
canvas.set(box_cross - 1, y, Cell::node('│'));
|
||||
}
|
||||
for (j, line) in lines.iter().enumerate() {
|
||||
let (x, y) = if horizontal {
|
||||
(start + 2, j + 1)
|
||||
} else {
|
||||
(2, start + j + 1)
|
||||
};
|
||||
put_text(&mut canvas.cells[y], x, line)?;
|
||||
}
|
||||
}
|
||||
let endpoints = graph
|
||||
.edges
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, edge)| {
|
||||
let offset = |node: usize, port: usize| {
|
||||
starts[node]
|
||||
+ if horizontal {
|
||||
1 + port * stride
|
||||
} else {
|
||||
labels[node].len() + 1 + port
|
||||
}
|
||||
};
|
||||
(offset(edge.from, ports[i].0), offset(edge.to, ports[i].1))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// Paint lanes first so every crossing is independent of iteration order.
|
||||
for (i, edge) in graph.edges.iter().enumerate() {
|
||||
let (source, target) = endpoints[i];
|
||||
for y in source.min(target) + 1..source.max(target) {
|
||||
canvas.set(
|
||||
first_lane + 2 * i,
|
||||
y,
|
||||
Cell::edge(if edge.dashed { '┆' } else { '│' }),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (i, edge) in graph.edges.iter().enumerate() {
|
||||
let (source, target) = endpoints[i];
|
||||
let lane = first_lane + 2 * i;
|
||||
for y in [source, target] {
|
||||
for x in box_cross..lane {
|
||||
let ch = if matches!(canvas.get(x, y), '│' | '┆') {
|
||||
'╪'
|
||||
} else if edge.dashed {
|
||||
'┄'
|
||||
} else {
|
||||
'─'
|
||||
};
|
||||
canvas.set(x, y, Cell::edge(ch));
|
||||
}
|
||||
}
|
||||
canvas.set(box_cross - 1, source, Cell::node('├'));
|
||||
canvas.set(box_cross - 1, target, Cell::node('├'));
|
||||
canvas.set(box_cross, source, Cell::edge(edge.source_tip));
|
||||
canvas.set(box_cross, target, Cell::edge(edge.target_tip));
|
||||
canvas.set(
|
||||
lane,
|
||||
source,
|
||||
Cell::edge(if source < target { '┐' } else { '┘' }),
|
||||
);
|
||||
canvas.set(
|
||||
lane,
|
||||
target,
|
||||
Cell::edge(if source < target { '┘' } else { '┐' }),
|
||||
);
|
||||
for (port, label) in [(source, &edge.label), (target, &edge.target_label)] {
|
||||
let (x, y) = if horizontal {
|
||||
(port + 1, box_cross + 1)
|
||||
} else {
|
||||
(box_cross + 2, port)
|
||||
};
|
||||
put_text(&mut canvas.cells[y], x, label)?;
|
||||
}
|
||||
}
|
||||
Ok(finish(canvas.cells))
|
||||
}
|
||||
|
||||
struct Canvas {
|
||||
cells: Vec<Vec<Cell>>,
|
||||
horizontal: bool,
|
||||
}
|
||||
|
||||
impl Canvas {
|
||||
fn set(&mut self, across: usize, along: usize, mut cell: Cell) {
|
||||
if self.horizontal {
|
||||
cell.symbol = transpose(cell.symbol);
|
||||
self.cells[across][along] = cell;
|
||||
} else {
|
||||
self.cells[along][across] = cell;
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, across: usize, along: usize) -> char {
|
||||
if self.horizontal {
|
||||
transpose(self.cells[across][along].symbol)
|
||||
} else {
|
||||
self.cells[along][across].symbol
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transpose(ch: char) -> char {
|
||||
match ch {
|
||||
'─' => '│',
|
||||
'│' => '─',
|
||||
'┄' => '┆',
|
||||
'┆' => '┄',
|
||||
'┐' => '└',
|
||||
'└' => '┐',
|
||||
'╮' => '╰',
|
||||
'╰' => '╮',
|
||||
'├' => '┬',
|
||||
'┬' => '├',
|
||||
'◄' => '▲',
|
||||
'▲' => '◄',
|
||||
'◁' => '△',
|
||||
'△' => '◁',
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn put_text(row: &mut [Cell], mut column: usize, text: &str) -> Result<(), RenderError> {
|
||||
for ch in text.chars() {
|
||||
let width = UnicodeWidthChar::width(ch).ok_or(RenderError::Unsupported)?;
|
||||
row[column] = Cell {
|
||||
symbol: ch,
|
||||
role: Role::Text,
|
||||
};
|
||||
row[column + 1..column + width].fill(Cell {
|
||||
symbol: '\0',
|
||||
role: Role::Text,
|
||||
});
|
||||
column += width;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
477
codex-rs/mermaid/src/families_tests.rs
Normal file
477
codex-rs/mermaid/src/families_tests.rs
Normal file
@@ -0,0 +1,477 @@
|
||||
//! End-to-end grammar, topology, and rendered output checks for each supported family.
|
||||
|
||||
use crate::RenderError;
|
||||
use crate::render;
|
||||
use pretty_assertions::assert_eq;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
const SEQUENCE: &str = "sequenceDiagram
|
||||
actor U as Buyer
|
||||
participant A as API
|
||||
participant S as 库存
|
||||
participant P as Payments
|
||||
U->>A: data[0] = {x: 1}
|
||||
A->>S: Reserve items
|
||||
S-->>A: say \"hello\" | C:\\tmp
|
||||
opt Items reserved
|
||||
loop Up to 3 attempts
|
||||
A->>P: Charge card
|
||||
P->>P: Check fraud
|
||||
P-->>A: Payment status
|
||||
alt Approved
|
||||
Note over A,P: Payment recorded
|
||||
A-->>U: Order confirmed
|
||||
else Declined
|
||||
A->>S: Release items
|
||||
A-->>U: Payment failed
|
||||
end
|
||||
end
|
||||
end";
|
||||
|
||||
const STATE: &str = "stateDiagram-v2
|
||||
state \"Payment pending\" as Charging
|
||||
[*] --> Draft
|
||||
Draft --> Validating: submit
|
||||
Validating --> Charging: [ready]
|
||||
Validating --> Rejected: invalid
|
||||
Charging --> Packing: paid
|
||||
Charging --> Rejected: declined
|
||||
Packing --> Shipped: dispatch
|
||||
Shipped --> Delivered: received
|
||||
Delivered --> [*]
|
||||
Rejected --> Draft: revise
|
||||
Charging: Retry up to 3 times
|
||||
Draft: Order drafted
|
||||
Draft: Awaiting submission";
|
||||
|
||||
const CLASS: &str = "classDiagram
|
||||
class order {
|
||||
+int[] ids
|
||||
+String a;b
|
||||
+submit()
|
||||
+cancel()
|
||||
}
|
||||
class LineItem {
|
||||
+int quantity
|
||||
+Decimal price
|
||||
+subtotal()
|
||||
}
|
||||
class Payment {
|
||||
+Decimal amount
|
||||
+authorize()
|
||||
}
|
||||
class CardPayment {
|
||||
+String lastFour
|
||||
+authorize()
|
||||
}
|
||||
order \"1\" *-- \"1..*\" LineItem : contains
|
||||
order \"1\" --> \"1\" Payment : pays with
|
||||
Payment <|-- CardPayment
|
||||
CardPayment ..order : updates";
|
||||
|
||||
const ER: &str = "erDiagram
|
||||
CUSTOMER ||--o{ ORDER : places
|
||||
ORDER ||--|{ LINE_ITEM : contains
|
||||
PRODUCT ||..o{ LINE_ITEM : appears_in
|
||||
CUSTOMER {
|
||||
int id PK
|
||||
string email UK
|
||||
string name
|
||||
}
|
||||
ORDER {
|
||||
int id PK
|
||||
int customer_id FK
|
||||
string status
|
||||
}
|
||||
LINE_ITEM {
|
||||
int order_id PK, FK \"order key\"
|
||||
int product_id PK, FK
|
||||
int quantity
|
||||
}
|
||||
PRODUCT {
|
||||
int id PK
|
||||
string name
|
||||
decimal price
|
||||
}";
|
||||
|
||||
#[test]
|
||||
fn complex_families() {
|
||||
for (name, source) in [
|
||||
("sequence", SEQUENCE),
|
||||
("state", STATE),
|
||||
("class", CLASS),
|
||||
("er", ER),
|
||||
] {
|
||||
let output = render(source, /*max_width*/ 180).unwrap();
|
||||
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
||||
assert_eq!(render(source, width), Ok(output.clone()));
|
||||
assert_eq!(render(source, width - 1), Err(RenderError::TooWide));
|
||||
insta::assert_snapshot!(name, output);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_labels_and_later_declarations() {
|
||||
for direction in ["TD", "BT", "LR", "RL"] {
|
||||
let source = format!(
|
||||
"%% heading\ngraph {direction}; A -->|准备| B; A[请求]; B{{Réponse?}}; B -->|retry| A; B --> C[Ship 🚀]"
|
||||
);
|
||||
let output = render(&source, /*max_width*/ 160).unwrap();
|
||||
for label in ["请求", "Réponse?", "Ship 🚀", "准备", "retry"] {
|
||||
assert!(output.contains(label), "{direction}: {label}");
|
||||
}
|
||||
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
||||
assert_eq!(render(&source, width), Ok(output.clone()));
|
||||
assert_eq!(render(&source, width - 1), Err(RenderError::TooWide));
|
||||
if direction == "LR" {
|
||||
insta::assert_snapshot!("LR", output);
|
||||
}
|
||||
}
|
||||
for descriptions in [
|
||||
vec!["S: Ready"],
|
||||
vec!["S: Ready", "S: Working"],
|
||||
vec![r#"state "Ready" as S"#, "S: Working"],
|
||||
vec!["S: Ready", r#"state "Working" as S"#],
|
||||
vec![r#"state "Ready" as S"#, r#"state "Working" as S"#],
|
||||
] {
|
||||
// References before and after descriptions must retain the same state identity.
|
||||
let mut body = vec!["S --> T"];
|
||||
body.extend(&descriptions);
|
||||
body.push("T --> S");
|
||||
let graph = crate::state::parse(&body).unwrap();
|
||||
let mut expected = crate::state::parse(&["S --> T", "T --> S"]).unwrap();
|
||||
expected.nodes[0] = crate::Node {
|
||||
id: "S".to_owned(),
|
||||
label: "Ready".to_owned(),
|
||||
shape: crate::Shape::Rectangle,
|
||||
declared: true,
|
||||
members: if descriptions.len() == 1 {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec!["Working".to_owned()]
|
||||
},
|
||||
};
|
||||
assert_eq!(graph, expected, "{descriptions:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_relationship_endpoints() {
|
||||
for (operator, source_tip, target_tip, dashed) in [
|
||||
("<|--", '◁', '─', false),
|
||||
("*--", '◆', '─', false),
|
||||
("o--", '◇', '─', false),
|
||||
("-->", '─', '◄', false),
|
||||
("--", '─', '─', false),
|
||||
("..>", '─', '◄', true),
|
||||
("..|>", '─', '◁', true),
|
||||
("..", '─', '─', true),
|
||||
("<--", '◄', '─', false),
|
||||
("--*", '─', '◆', false),
|
||||
("--o", '─', '◇', false),
|
||||
("--|>", '─', '◁', false),
|
||||
] {
|
||||
let output = render(
|
||||
&format!("classDiagram; A \"one\" {operator} \"many\" B : uses"),
|
||||
/*max_width*/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let ports = output
|
||||
.lines()
|
||||
.filter(|line| line.contains('├'))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
ports[0].contains(&format!("├{source_tip}")),
|
||||
"{operator}: {output}"
|
||||
);
|
||||
assert!(
|
||||
ports[1].contains(&format!("├{target_tip}")),
|
||||
"{operator}: {output}"
|
||||
);
|
||||
assert!(ports[0].contains("(one) uses"));
|
||||
assert!(ports[1].contains("(many)"));
|
||||
assert_eq!(output.contains('┆'), dashed);
|
||||
}
|
||||
for (operator, source_tip, target_tip, dashed) in [
|
||||
("---", '─', '─', false),
|
||||
("-.->", '─', '◄', true),
|
||||
("-.-", '─', '─', true),
|
||||
("<-->", '◄', '◄', false),
|
||||
("<-.->", '◄', '◄', true),
|
||||
] {
|
||||
let output = render(
|
||||
&format!("flowchart; A{operator}|uses|B"),
|
||||
/*max_width*/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let ports = output
|
||||
.lines()
|
||||
.filter(|line| line.contains('├'))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
ports[0].contains(&format!("├{source_tip}")),
|
||||
"{operator}: {output}"
|
||||
);
|
||||
assert!(
|
||||
ports[1].contains(&format!("├{target_tip}")),
|
||||
"{operator}: {output}"
|
||||
);
|
||||
assert!(ports[0].contains("uses"));
|
||||
assert_eq!(output.contains('┆'), dashed);
|
||||
}
|
||||
for source in [
|
||||
"classDiagram\nclass A; A --> B : {ok}",
|
||||
"classDiagram\nclass A; class B {\n+id\n}",
|
||||
] {
|
||||
assert_eq!(
|
||||
render(source, /*max_width*/ 100).unwrap(),
|
||||
render(&source.replace(';', "\n"), /*max_width*/ 100).unwrap(),
|
||||
);
|
||||
}
|
||||
let source = "classDiagram\nclass A {\nstring a;b\nObject[] elementData\n}\nA : +get()";
|
||||
let statements = crate::syntax::statements(source).unwrap();
|
||||
assert_eq!(
|
||||
crate::relations::parse(statements[0], &statements[1..]).unwrap(),
|
||||
crate::Graph {
|
||||
nodes: vec![crate::Node {
|
||||
id: "A".into(),
|
||||
label: "A".into(),
|
||||
shape: crate::Shape::Rectangle,
|
||||
declared: false,
|
||||
members: vec![
|
||||
"string a;b".into(),
|
||||
"Object[] elementData".into(),
|
||||
"+get()".into()
|
||||
],
|
||||
}],
|
||||
..crate::Graph::default()
|
||||
}
|
||||
);
|
||||
for (line, target, target_tip, target_label, dashed) in [
|
||||
("A --orange", "orange", '─', "", false),
|
||||
("A ..o_range", "o_range", '─', "", true),
|
||||
("A --o B", "B", '◇', "", false),
|
||||
(r#"A ..o"many" B"#, "B", '◇', "(many)", true),
|
||||
] {
|
||||
let graph = crate::relations::parse("classDiagram", &[line]).unwrap();
|
||||
let mut expected = crate::Graph::default();
|
||||
let from = expected.node("A").unwrap();
|
||||
let to = expected.node(target).unwrap();
|
||||
expected.edges.push(crate::Edge {
|
||||
from,
|
||||
to,
|
||||
label: String::new(),
|
||||
target_label: target_label.to_owned(),
|
||||
source_tip: '─',
|
||||
target_tip,
|
||||
dashed,
|
||||
});
|
||||
assert_eq!(graph, expected, "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn er_cardinalities() {
|
||||
for (left, source_card) in [
|
||||
("||", "1"),
|
||||
("|o", "0..1"),
|
||||
("}|", "1..many"),
|
||||
("}o", "0..many"),
|
||||
] {
|
||||
for (right, target_card) in [
|
||||
("||", "1"),
|
||||
("o|", "0..1"),
|
||||
("|{", "1..many"),
|
||||
("o{", "0..many"),
|
||||
] {
|
||||
let output = render(
|
||||
&format!("erDiagram; A {left}--{right} B : owns"),
|
||||
/*max_width*/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let ports = output
|
||||
.lines()
|
||||
.filter(|line| line.contains('├'))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(ports[0].contains(&format!("({source_card}) owns")));
|
||||
assert!(ports[1].contains(&format!("({target_card})")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_incomplete_and_unsupported_families() {
|
||||
for source in [
|
||||
"sequenceDiagram; A->>B: hello; nonsense",
|
||||
"sequenceDiagram; A->>B: hello; activate B",
|
||||
"sequenceDiagram; participant A as x; participant A as y",
|
||||
"sequenceDiagram; alt ready; A->>B: hi",
|
||||
"sequenceDiagram; A->>B: hi; end",
|
||||
"sequenceDiagram; loop retry; else no; end",
|
||||
"sequenceDiagram; alt one; else two; else three; end",
|
||||
"sequenceDiagram; A->>B: <br/>",
|
||||
"sequenceDiagram; A->>B: \u{1b}[31m",
|
||||
"sequenceDiagram; participant A as e\u{301}",
|
||||
"stateDiagram-v2; state Processing {; A-->B; }",
|
||||
"stateDiagram-v2; A --> B: ok; garbage text",
|
||||
"stateDiagram-v2; accDescr: Order lifecycle; [*] --> Ready",
|
||||
"stateDiagram; ACCDESCR: Order lifecycle; [*] --> Ready",
|
||||
"stateDiagram-v2; A:::highlight; A --> B",
|
||||
"stateDiagram-v2; A --> B:::highlight",
|
||||
"classDiagram; accTitle: Account model; class Account",
|
||||
"classDiagram; class A {; +foo()",
|
||||
"classDiagram; class A; A --? B",
|
||||
"classDiagram; A --> B; click A",
|
||||
"classDiagram; class A {; +<html>; }",
|
||||
"erDiagram; A ||--o{ B",
|
||||
"erDiagram; A ||--|| B: \"owns\"",
|
||||
"erDiagram; A {; string value \"x\"junk\"; }",
|
||||
"classDiagram\nclass A {\nstring a;b }\n}",
|
||||
"erDiagram; A ||--?? B : owns",
|
||||
"erDiagram; A {; int x KEY; }",
|
||||
"erDiagram; A {; int x PK \"open comment; }",
|
||||
"erDiagram; A {; int x; }; A ||--|| B : uses; trailing junk",
|
||||
"erDiagram; accDescr {; A model; }; CUSTOMER",
|
||||
"erDiagram; ACCDESCR {; A model; }; CUSTOMER",
|
||||
"erDiagram; A ||--|| B:::highlight : owns",
|
||||
"%%{init: {}}%%\nclassDiagram; class A",
|
||||
] {
|
||||
assert_eq!(
|
||||
render(source, /*max_width*/ 200),
|
||||
Err(RenderError::Unsupported),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_names_and_style_text_remain_valid_in_content() {
|
||||
for source in [
|
||||
"classDiagram; class accTitle {\n +id\n }\n class accDescr {\n +id\n }",
|
||||
"classDiagram; class A; A: ::: literal; A --> B: ::: literal",
|
||||
"erDiagram; accTitle {; int id; }",
|
||||
"erDiagram; A ||--|| B: ::: literal",
|
||||
"stateDiagram-v2; A: text ::: literal; A --> B: ::: literal",
|
||||
] {
|
||||
assert!(render(source, /*max_width*/ 200).is_ok(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn family_limits() {
|
||||
for source in [
|
||||
format!(
|
||||
"sequenceDiagram; {}",
|
||||
(0..9)
|
||||
.map(|i| format!("participant P{i};"))
|
||||
.collect::<String>()
|
||||
),
|
||||
format!("sequenceDiagram; {}", "A->>B: msg;".repeat(65)),
|
||||
format!(
|
||||
"sequenceDiagram; {} A->>B: msg; {}",
|
||||
"loop retry;".repeat(5),
|
||||
"end;".repeat(5)
|
||||
),
|
||||
format!("classDiagram; class A {{\n {} }}", "+field\n".repeat(17)),
|
||||
format!("erDiagram; A {{; {} }}", "int id;".repeat(17)),
|
||||
format!("stateDiagram-v2; {}", "A --> B;".repeat(25)),
|
||||
format!("stateDiagram-v2\n{}", "S: Description\n".repeat(18)),
|
||||
format!(
|
||||
"stateDiagram-v2\n{}",
|
||||
"state \"Description\" as S\n".repeat(18)
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
render(&source, /*max_width*/ usize::MAX),
|
||||
Err(RenderError::Limit),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_sources_and_terminal_widths() {
|
||||
// Exercise incomplete streamed source at every UTF-8 boundary, including inside control blocks.
|
||||
for source in [SEQUENCE, STATE, CLASS, ER, "sequenceDiagram; A->>B: 请求"] {
|
||||
for end in source.char_indices().map(|(index, _)| index) {
|
||||
if let Ok(output) = render(&source[..end], /*max_width*/ 180) {
|
||||
assert!(output.lines().all(|line| line.width() <= 180));
|
||||
assert!(!output.chars().any(|ch| ch.is_control() && ch != '\n'));
|
||||
}
|
||||
}
|
||||
}
|
||||
for source in [
|
||||
"sequenceDiagram; A->>B: hi",
|
||||
"sequenceDiagram; A->>A: self",
|
||||
"sequenceDiagram; Note over A: memo",
|
||||
"stateDiagram-v2; state \"a;b\" as A; A-->B: [ready]",
|
||||
"erDiagram; A {; string value \"a;b\"; }",
|
||||
] {
|
||||
let output = render(source, /*max_width*/ 100).unwrap();
|
||||
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
||||
assert_eq!(render(source, width), Ok(output));
|
||||
assert_eq!(render(source, width - 1), Err(RenderError::TooWide));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_arrows_preserve_sender_recipient_and_style() {
|
||||
for (operator, forward, reverse, dashed) in [
|
||||
("->>", '▶', '◀', false),
|
||||
("-->>", '▶', '◀', true),
|
||||
("->", '─', '─', false),
|
||||
("-->", '┄', '┄', true),
|
||||
("-x", 'x', 'x', false),
|
||||
("--x", 'x', 'x', true),
|
||||
] {
|
||||
for (from, to, tip) in [
|
||||
("A", "B", forward),
|
||||
("B", "A", reverse),
|
||||
("B", "B", reverse),
|
||||
] {
|
||||
let output = render(
|
||||
&format!(
|
||||
"sequenceDiagram; participant A; participant B; {from}{operator}{to}: msg"
|
||||
),
|
||||
/*max_width*/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let rows = output
|
||||
.lines()
|
||||
.map(|line| line.chars().collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>();
|
||||
let a = rows[1].iter().position(|ch| *ch == 'A').unwrap();
|
||||
let b = rows[1].iter().position(|ch| *ch == 'B').unwrap();
|
||||
let recipient = if to == "A" { a } else { b };
|
||||
let row = if from == to { 5 } else { 4 };
|
||||
assert_eq!(rows[row][recipient], tip, "{from}{operator}{to}");
|
||||
assert_eq!(rows[row].contains(&'┄'), dashed);
|
||||
}
|
||||
}
|
||||
let source = "sequenceDiagram; A->>B: say \"hello; B->>A: world\"";
|
||||
assert_eq!(
|
||||
render(source, /*max_width*/ 180).unwrap(),
|
||||
render(&source.replace(';', "\n"), /*max_width*/ 180).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_limit_applies_even_with_unlimited_caller_width() {
|
||||
let graph = format!(
|
||||
"graph LR; {}",
|
||||
format!("A-->|{}|B;", "x".repeat(40)).repeat(24)
|
||||
);
|
||||
let sequence = format!(
|
||||
"sequenceDiagram; {} {}",
|
||||
(0..8)
|
||||
.map(|i| format!("participant P{i};"))
|
||||
.collect::<String>(),
|
||||
format!("P0->>P7: {};", "x".repeat(40)).repeat(64)
|
||||
);
|
||||
for source in [graph, sequence] {
|
||||
assert_eq!(
|
||||
render(&source, /*max_width*/ usize::MAX),
|
||||
Err(RenderError::Limit)
|
||||
);
|
||||
}
|
||||
}
|
||||
172
codex-rs/mermaid/src/lib.rs
Normal file
172
codex-rs/mermaid/src/lib.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! Bounded, terminal-native Mermaid diagram prototype.
|
||||
//!
|
||||
//! Supports flowcharts, sequences, states, classes, and entity relationships.
|
||||
//! Graph edges own separate lanes and endpoint positions. Crossings never join routes. Unsupported
|
||||
//! syntax and outputs exceeding the caller's width return errors, leaving source fallback to
|
||||
//! the caller. This crate performs no I/O and does not depend on a Mermaid implementation.
|
||||
|
||||
mod draw;
|
||||
mod output;
|
||||
mod parse;
|
||||
mod relations;
|
||||
mod sequence;
|
||||
mod state;
|
||||
mod syntax;
|
||||
|
||||
pub use output::Role;
|
||||
pub use output::Span;
|
||||
use std::fmt;
|
||||
|
||||
const MAX_SOURCE: usize = 16 * 1024;
|
||||
const MAX_NODES: usize = 16;
|
||||
const MAX_EDGES: usize = 24;
|
||||
const MAX_LABEL: usize = 40;
|
||||
const MAX_CELLS: usize = 64 * 1024;
|
||||
|
||||
/// A diagram cannot be faithfully represented by this bounded prototype.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RenderError {
|
||||
/// Syntax or text is outside the explicitly supported subset.
|
||||
Unsupported,
|
||||
/// A source, diagram, label, or canvas limit was exceeded.
|
||||
Limit,
|
||||
/// The complete diagram exceeds the supplied display width.
|
||||
TooWide,
|
||||
}
|
||||
|
||||
impl fmt::Display for RenderError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Unsupported => "unsupported Mermaid syntax or label",
|
||||
Self::Limit => "diagram exceeds prototype limits",
|
||||
Self::TooWide => "diagram exceeds available display width",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RenderError {}
|
||||
|
||||
/// Render a bounded subset of Mermaid as plain Unicode text.
|
||||
///
|
||||
/// Supports flowcharts, sequence diagrams, flat state diagrams, class diagrams, and ER diagrams.
|
||||
/// See the crate README for each grammar and its limits. Unknown syntax, unsafe terminal text,
|
||||
/// and diagrams exceeding `max_width` return errors; no partial result is returned.
|
||||
pub fn render(source: &str, max_width: usize) -> Result<String, RenderError> {
|
||||
Ok(render_spans(source, max_width)?
|
||||
.into_iter()
|
||||
.map(|line| line.into_iter().map(|span| span.text).collect::<String>())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
|
||||
/// Render the same bounded diagram as lines of semantic spans for caller-provided styling.
|
||||
pub fn render_spans(source: &str, max_width: usize) -> Result<Vec<Vec<Span>>, RenderError> {
|
||||
if source.len() > MAX_SOURCE {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
let statements = syntax::statements(source)?;
|
||||
let (header, body) = statements.split_first().ok_or(RenderError::Unsupported)?;
|
||||
match *header {
|
||||
"sequenceDiagram" => sequence::render(body, max_width),
|
||||
"stateDiagram-v2" | "stateDiagram" | "classDiagram" | "erDiagram" => {
|
||||
draw::render(&relations::parse(header, body)?, max_width)
|
||||
}
|
||||
_ => draw::render(&parse::parse(header, body)?, max_width),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
enum Direction {
|
||||
#[default]
|
||||
Down,
|
||||
Up,
|
||||
Right,
|
||||
Left,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
fn parse(text: &str) -> Result<Self, RenderError> {
|
||||
match text {
|
||||
"TD" | "TB" => Ok(Self::Down),
|
||||
"BT" => Ok(Self::Up),
|
||||
"LR" => Ok(Self::Right),
|
||||
"RL" => Ok(Self::Left),
|
||||
_ => Err(RenderError::Unsupported),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Node shapes supported by the terminal renderer.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Shape {
|
||||
/// A rectangular node, such as `A[Work]`.
|
||||
Rectangle,
|
||||
/// A decision node (`A{Done?}`), rendered with a `◇` marker inside a box.
|
||||
Decision,
|
||||
/// A stadium node (`A([Start])`), rendered as a box with rounded corners.
|
||||
Stadium,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Node {
|
||||
id: String,
|
||||
label: String,
|
||||
shape: Shape,
|
||||
declared: bool,
|
||||
members: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Edge {
|
||||
from: usize,
|
||||
to: usize,
|
||||
label: String,
|
||||
target_label: String,
|
||||
source_tip: char,
|
||||
target_tip: char,
|
||||
dashed: bool,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
fn directed(from: usize, to: usize, label: String) -> Self {
|
||||
Self {
|
||||
from,
|
||||
to,
|
||||
label,
|
||||
target_label: String::new(),
|
||||
source_tip: '─',
|
||||
target_tip: '◄',
|
||||
dashed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct Graph {
|
||||
direction: Direction,
|
||||
nodes: Vec<Node>,
|
||||
edges: Vec<Edge>,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
fn node(&mut self, id: &str) -> Result<usize, RenderError> {
|
||||
if let Some(index) = self.nodes.iter().position(|node| node.id == id) {
|
||||
return Ok(index);
|
||||
}
|
||||
if self.nodes.len() == MAX_NODES {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
self.nodes.push(Node {
|
||||
id: id.to_owned(),
|
||||
label: id.to_owned(),
|
||||
shape: Shape::Rectangle,
|
||||
declared: false,
|
||||
members: Vec::new(),
|
||||
});
|
||||
Ok(self.nodes.len() - 1)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
69
codex-rs/mermaid/src/output.rs
Normal file
69
codex-rs/mermaid/src/output.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! Semantic spans for theme-independent diagram output; drawing cells never contain ANSI escapes.
|
||||
|
||||
/// The diagram element a caller can style with its own theme.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
Node,
|
||||
Edge,
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Adjacent characters with one semantic role, independent of terminal styling.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub text: String,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Cell {
|
||||
pub symbol: char,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
impl Cell {
|
||||
pub(super) fn edge(symbol: char) -> Self {
|
||||
Self {
|
||||
symbol,
|
||||
role: Role::Edge,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn node(symbol: char) -> Self {
|
||||
Self {
|
||||
symbol,
|
||||
role: Role::Node,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(rows: Vec<Vec<Cell>>) -> Vec<Vec<Span>> {
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let mut spans: Vec<Span> = Vec::new();
|
||||
for Cell { symbol, role } in row {
|
||||
if symbol == '\0' {
|
||||
continue;
|
||||
}
|
||||
if let Some(last) = spans.last_mut()
|
||||
&& last.role == role
|
||||
{
|
||||
last.text.push(symbol);
|
||||
} else {
|
||||
spans.push(Span {
|
||||
text: symbol.to_string(),
|
||||
role,
|
||||
});
|
||||
}
|
||||
}
|
||||
while let Some(last) = spans.last_mut() {
|
||||
last.text.truncate(last.text.trim_end().len());
|
||||
if !last.text.is_empty() {
|
||||
break;
|
||||
}
|
||||
spans.pop();
|
||||
}
|
||||
spans
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
227
codex-rs/mermaid/src/parse.rs
Normal file
227
codex-rs/mermaid/src/parse.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
//! Strict parser for a small flowchart grammar; every non-comment byte must be consumed.
|
||||
//! Node groups expand into explicit edges within the graph edge cap.
|
||||
|
||||
use super::Direction;
|
||||
use super::Edge;
|
||||
use super::Graph;
|
||||
use super::MAX_EDGES;
|
||||
use super::MAX_LABEL;
|
||||
use super::RenderError;
|
||||
use super::Shape;
|
||||
use super::syntax::delimited_label;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
|
||||
let tokens = header.split_whitespace().collect::<Vec<_>>();
|
||||
let direction = match tokens.as_slice() {
|
||||
["flowchart" | "graph"] => Direction::Down,
|
||||
["flowchart" | "graph", direction] => Direction::parse(direction)?,
|
||||
_ => return Err(RenderError::Unsupported),
|
||||
};
|
||||
let mut graph = Graph {
|
||||
direction,
|
||||
..Graph::default()
|
||||
};
|
||||
for statement in body {
|
||||
let mut rest = *statement;
|
||||
let mut from = nodes(&mut rest, &mut graph)?;
|
||||
while !rest.trim_start().is_empty() {
|
||||
rest = rest.trim_start();
|
||||
let mut label = String::new();
|
||||
let (source_tip, target_tip, dashed) = if let Some((after, source, target, dashed)) = [
|
||||
("<-.->", '◄', '◄', true),
|
||||
("<-->", '◄', '◄', false),
|
||||
("-.->", '─', '◄', true),
|
||||
("-.-", '─', '─', true),
|
||||
("-->", '─', '◄', false),
|
||||
("---", '─', '─', false),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(token, source, target, dashed)| {
|
||||
rest.strip_prefix(token)
|
||||
.map(|after| (after, source, target, dashed))
|
||||
}) {
|
||||
// Circle/cross tips are unsupported; without a space they are not node IDs.
|
||||
if target == '─' && after.starts_with(['o', 'x']) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
rest = after.trim_start();
|
||||
if let Some(after) = rest.strip_prefix('|') {
|
||||
let (text, remaining) = delimited_label(after, "|")?;
|
||||
label = flowchart_label(text)?.to_owned();
|
||||
check_label(&label)?;
|
||||
rest = remaining;
|
||||
}
|
||||
(source, target, dashed)
|
||||
} else {
|
||||
let (after, stem, dashed) = if let Some(after) = rest.strip_prefix("--") {
|
||||
(after, "--", false)
|
||||
} else if let Some(after) = rest.strip_prefix("-.") {
|
||||
(after, ".-", true)
|
||||
} else {
|
||||
return Err(RenderError::Unsupported);
|
||||
};
|
||||
// Spaced labels keep endpoint markers out of the text. Stop at the first
|
||||
// closing stem instead of swallowing an unsupported edge and its target.
|
||||
let (text, remaining) = after.split_once(stem).ok_or(RenderError::Unsupported)?;
|
||||
if !text.starts_with(char::is_whitespace) || !text.ends_with(char::is_whitespace) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
rest = remaining
|
||||
.strip_prefix('>')
|
||||
.ok_or(RenderError::Unsupported)?;
|
||||
label = flowchart_label(text.trim())?.to_owned();
|
||||
check_label(&label)?;
|
||||
('─', '◄', dashed)
|
||||
};
|
||||
let to = nodes(&mut rest, &mut graph)?;
|
||||
// Check the Cartesian expansion before allocating edges, including repeated IDs.
|
||||
if from.len() * to.len() > MAX_EDGES - graph.edges.len() {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
for &from in &from {
|
||||
for &to in &to {
|
||||
graph.edges.push(Edge {
|
||||
from,
|
||||
to,
|
||||
label: label.clone(),
|
||||
target_label: String::new(),
|
||||
source_tip,
|
||||
target_tip,
|
||||
dashed,
|
||||
});
|
||||
}
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
if graph.nodes.is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn nodes(rest: &mut &str, graph: &mut Graph) -> Result<Vec<usize>, RenderError> {
|
||||
let mut nodes = vec![node(rest, graph)?];
|
||||
while let Some(after) = rest.trim_start().strip_prefix('&') {
|
||||
if nodes.len() == MAX_EDGES {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
*rest = after;
|
||||
nodes.push(node(rest, graph)?);
|
||||
}
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
fn node(rest: &mut &str, graph: &mut Graph) -> Result<usize, RenderError> {
|
||||
let id = identifier(rest)?;
|
||||
// Reserved constructs must not be interpreted as ordinary node declarations.
|
||||
if matches!(
|
||||
id,
|
||||
"end" | "subgraph" | "direction" | "style" | "class" | "classDef" | "linkStyle" | "click"
|
||||
) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
// Longer shape delimiters must not become punctuation inside a simpler node.
|
||||
if ["[(", "[[", "[/", "[\\", "{{"]
|
||||
.iter()
|
||||
.any(|open| rest.starts_with(open))
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let declaration = match rest.chars().next() {
|
||||
Some('[') => Some(("[", "]", Shape::Rectangle)),
|
||||
Some('{') => Some(("{", "}", Shape::Decision)),
|
||||
Some('(') if rest.starts_with("([") => Some(("([", "])", Shape::Stadium)),
|
||||
_ => None,
|
||||
};
|
||||
let index = graph.node(id)?;
|
||||
if let Some((open, close, shape)) = declaration {
|
||||
let (label, remaining) = delimited_label(&rest[open.len()..], close)?;
|
||||
let label = flowchart_label(label)?
|
||||
.replace("<br>", "\n")
|
||||
.replace("<br/>", "\n")
|
||||
.replace("<br />", "\n");
|
||||
if label.trim().is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
for line in label.split('\n').filter(|line| !line.is_empty()) {
|
||||
check_label(line)?;
|
||||
}
|
||||
*rest = remaining;
|
||||
let node = &mut graph.nodes[index];
|
||||
if node.declared && (node.label != label || node.shape != shape) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
node.label = label;
|
||||
node.shape = shape;
|
||||
node.declared = true;
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn flowchart_label(label: &str) -> Result<&str, RenderError> {
|
||||
// Mermaid Markdown strings require rendering beyond ordinary quoted labels.
|
||||
if label.starts_with("\"`") {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let label = if let Some(quoted) = label.strip_prefix('"') {
|
||||
quoted.strip_suffix('"').ok_or(RenderError::Unsupported)?
|
||||
} else {
|
||||
if label.contains(['[', ']', '{', '}', '|']) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
label
|
||||
};
|
||||
if label.contains('"') {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
pub(super) fn check_label(label: &str) -> Result<(), RenderError> {
|
||||
// Markup needs deliberate decoding/layout; printable comparison operators are plain text.
|
||||
let markup = label.match_indices('<').any(|(index, _)| {
|
||||
let after = &label[index + 1..];
|
||||
after.starts_with(|ch: char| ch.is_ascii_alphabetic() || matches!(ch, '/' | '!' | '?'))
|
||||
});
|
||||
if markup
|
||||
|| label.trim().is_empty()
|
||||
|| label.chars().any(|ch| {
|
||||
ch.is_control()
|
||||
|| matches!(ch, '┌' | '┐' | '└' | '┘' | '├' | '┤' | '╪' | '◄')
|
||||
|| UnicodeWidthChar::width(ch).is_none_or(|width| width == 0)
|
||||
})
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
// Labels are drawn one Unicode scalar at a time. Reject ligatures whose string width differs
|
||||
// from those scalar widths rather than misaligning borders or underallocating the canvas.
|
||||
if label
|
||||
.chars()
|
||||
.filter_map(UnicodeWidthChar::width)
|
||||
.sum::<usize>()
|
||||
!= label.width()
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
if UnicodeWidthStr::width(label) > MAX_LABEL {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn identifier<'a>(rest: &mut &'a str) -> Result<&'a str, RenderError> {
|
||||
*rest = rest.trim_start();
|
||||
let len = rest
|
||||
.bytes()
|
||||
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
|
||||
.count();
|
||||
let id = &rest[..len];
|
||||
if id.is_empty() || !id.as_bytes()[0].is_ascii_alphabetic() || id.len() > MAX_LABEL {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
*rest = &rest[len..];
|
||||
Ok(id)
|
||||
}
|
||||
241
codex-rs/mermaid/src/relations.rs
Normal file
241
codex-rs/mermaid/src/relations.rs
Normal file
@@ -0,0 +1,241 @@
|
||||
//! Class and ER grammars, preserving members, endpoint cardinalities, and relationship kinds.
|
||||
|
||||
use super::Direction;
|
||||
use super::Edge;
|
||||
use super::Graph;
|
||||
use super::MAX_EDGES;
|
||||
use super::RenderError;
|
||||
use super::parse::check_label;
|
||||
use super::parse::identifier;
|
||||
|
||||
pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
|
||||
if matches!(header, "stateDiagram" | "stateDiagram-v2") {
|
||||
return super::state::parse(body);
|
||||
}
|
||||
let er = header == "erDiagram";
|
||||
let mut graph = Graph::default();
|
||||
let mut block = None;
|
||||
let mut direction = false;
|
||||
for &line in body {
|
||||
if let Some(index) = block {
|
||||
if line == "}" {
|
||||
block = None;
|
||||
} else {
|
||||
let member = if er {
|
||||
attribute(line)?
|
||||
} else {
|
||||
if line.contains(['{', '}']) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
check_label(line)?;
|
||||
line.to_owned()
|
||||
};
|
||||
let node: &mut super::Node = &mut graph.nodes[index];
|
||||
if node.members.len() == 16 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
node.members.push(member);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("direction ") {
|
||||
if direction {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
graph.direction = Direction::parse(value.trim())?;
|
||||
direction = true;
|
||||
continue;
|
||||
}
|
||||
let declaration = !er && line.starts_with("class ");
|
||||
let mut rest = line.strip_prefix("class ").filter(|_| !er).unwrap_or(line);
|
||||
let id = identifier(&mut rest)?;
|
||||
rest = rest.trim_start();
|
||||
let title = id == "accTitle" || er && id.eq_ignore_ascii_case("accTitle");
|
||||
let description = id == "accDescr" || er && id.eq_ignore_ascii_case("accDescr");
|
||||
if !declaration
|
||||
&& (title && rest.starts_with(':') || description && rest.starts_with([':', '{']))
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let from = graph.node(id)?;
|
||||
if rest == "{" && (er || declaration) {
|
||||
block = Some(from);
|
||||
continue;
|
||||
}
|
||||
if declaration || (er && rest.is_empty()) {
|
||||
if !rest.is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !er
|
||||
&& let Some(member) = rest
|
||||
.strip_prefix(':')
|
||||
.filter(|text| !text.starts_with("::"))
|
||||
{
|
||||
let member = member.trim();
|
||||
check_label(member)?;
|
||||
if graph.nodes[from].members.len() == 16 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
graph.nodes[from].members.push(member.to_owned());
|
||||
continue;
|
||||
}
|
||||
let source_card = if er {
|
||||
String::new()
|
||||
} else {
|
||||
cardinality(&mut rest)?
|
||||
};
|
||||
rest = rest.trim_start();
|
||||
let split = rest
|
||||
.find("--")
|
||||
.into_iter()
|
||||
.chain(rest.find(".."))
|
||||
.min()
|
||||
.ok_or(RenderError::Unsupported)?;
|
||||
if split > 2 {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let left = &rest[..split];
|
||||
let dashed = &rest[split..split + 2] == "..";
|
||||
rest = &rest[split + 2..];
|
||||
let (source_tip, target_tip, source_card, target_card) = if er {
|
||||
let source_card = match left {
|
||||
"||" => "1",
|
||||
"|o" => "0..1",
|
||||
"}|" => "1..many",
|
||||
"}o" => "0..many",
|
||||
_ => return Err(RenderError::Unsupported),
|
||||
}
|
||||
.to_owned();
|
||||
let right = rest.get(..2).ok_or(RenderError::Unsupported)?;
|
||||
let target_card = match right {
|
||||
"||" => "1",
|
||||
"o|" => "0..1",
|
||||
"|{" => "1..many",
|
||||
"o{" => "0..many",
|
||||
_ => return Err(RenderError::Unsupported),
|
||||
}
|
||||
.to_owned();
|
||||
rest = &rest[2..];
|
||||
('─', '─', source_card, target_card)
|
||||
} else {
|
||||
let source_tip = match left {
|
||||
"" => '─',
|
||||
"<" => '◄',
|
||||
"<|" => '◁',
|
||||
"*" => '◆',
|
||||
"o" => '◇',
|
||||
_ => return Err(RenderError::Unsupported),
|
||||
};
|
||||
let mut target_tip = '─';
|
||||
for (token, tip) in [("|>", '◁'), (">", '◄'), ("*", '◆'), ("o", '◇')] {
|
||||
if let Some(after) = rest.strip_prefix(token) {
|
||||
// A longer identifier wins over the single-letter aggregation token.
|
||||
if token == "o"
|
||||
&& after.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '_')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
target_tip = tip;
|
||||
rest = after;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let target_card = cardinality(&mut rest)?;
|
||||
(source_tip, target_tip, source_card, target_card)
|
||||
};
|
||||
let to = graph.node(identifier(&mut rest)?)?;
|
||||
rest = rest.trim();
|
||||
let label = if let Some(label) = rest
|
||||
.strip_prefix(':')
|
||||
.filter(|text| !text.starts_with("::"))
|
||||
{
|
||||
let label = label.trim();
|
||||
// ER quotes delimit a token; keep fallback until that grammar is normalized.
|
||||
if er && label.contains('"') {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
check_label(label)?;
|
||||
label.to_owned()
|
||||
} else if !rest.is_empty() || er {
|
||||
return Err(RenderError::Unsupported);
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
if graph.edges.len() == MAX_EDGES {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
let label = match (source_card.is_empty(), label.is_empty()) {
|
||||
(true, _) => label,
|
||||
(false, true) => format!("({source_card})"),
|
||||
(false, false) => format!("({source_card}) {label}"),
|
||||
};
|
||||
graph.edges.push(Edge {
|
||||
from,
|
||||
to,
|
||||
label,
|
||||
source_tip,
|
||||
target_tip,
|
||||
dashed,
|
||||
target_label: if target_card.is_empty() {
|
||||
target_card
|
||||
} else {
|
||||
format!("({target_card})")
|
||||
},
|
||||
});
|
||||
}
|
||||
if block.is_some() || graph.nodes.is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn cardinality(rest: &mut &str) -> Result<String, RenderError> {
|
||||
*rest = rest.trim_start();
|
||||
if let Some(after) = rest.strip_prefix('"') {
|
||||
let (value, after) = after.split_once('"').ok_or(RenderError::Unsupported)?;
|
||||
check_label(value)?;
|
||||
*rest = after;
|
||||
Ok(value.to_owned())
|
||||
} else {
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute(line: &str) -> Result<String, RenderError> {
|
||||
let mut rest = line;
|
||||
let data_type = identifier(&mut rest)?;
|
||||
if !rest.starts_with(char::is_whitespace) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let name = identifier(&mut rest)?;
|
||||
let (keys, comment) = if let Some((keys, comment)) = rest.trim().split_once('"') {
|
||||
let comment = comment.strip_suffix('"').ok_or(RenderError::Unsupported)?;
|
||||
if comment.contains('"') {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
check_label(comment)?;
|
||||
(keys.trim(), Some(comment))
|
||||
} else {
|
||||
(rest.trim(), None)
|
||||
};
|
||||
if !keys.is_empty()
|
||||
&& !keys
|
||||
.split(',')
|
||||
.all(|key| matches!(key.trim(), "PK" | "FK" | "UK"))
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let mut result = format!("{data_type} {name}");
|
||||
if !keys.is_empty() {
|
||||
result.push(' ');
|
||||
result.push_str(keys);
|
||||
}
|
||||
if let Some(comment) = comment {
|
||||
result.push_str(" — ");
|
||||
result.push_str(comment);
|
||||
}
|
||||
check_label(&result)?;
|
||||
Ok(result)
|
||||
}
|
||||
306
codex-rs/mermaid/src/sequence.rs
Normal file
306
codex-rs/mermaid/src/sequence.rs
Normal file
@@ -0,0 +1,306 @@
|
||||
//! Bounded sequence timelines with ordered messages and explicitly nested control fragments.
|
||||
|
||||
use super::RenderError;
|
||||
use super::Span;
|
||||
use super::draw::put_text;
|
||||
use super::output::Cell;
|
||||
use super::output::finish;
|
||||
use super::parse::check_label;
|
||||
use super::parse::identifier;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Event {
|
||||
Message {
|
||||
from: usize,
|
||||
to: usize,
|
||||
text: String,
|
||||
dashed: bool,
|
||||
arrow: char,
|
||||
},
|
||||
Open(String),
|
||||
Branch(String),
|
||||
Close,
|
||||
Note {
|
||||
left: usize,
|
||||
right: usize,
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) fn render(body: &[&str], max_width: usize) -> Result<Vec<Vec<Span>>, RenderError> {
|
||||
let mut people: Vec<(String, String, bool)> = Vec::new();
|
||||
let mut events = Vec::new();
|
||||
let mut blocks = Vec::new();
|
||||
for &line in body {
|
||||
let mut rest = line;
|
||||
if let Some(after) = line
|
||||
.strip_prefix("participant ")
|
||||
.or_else(|| line.strip_prefix("actor "))
|
||||
{
|
||||
rest = after;
|
||||
let id = identifier(&mut rest)?;
|
||||
let label = if let Some(label) = rest.trim_start().strip_prefix("as ") {
|
||||
check_label(label)?;
|
||||
label
|
||||
} else if rest.trim().is_empty() {
|
||||
id
|
||||
} else {
|
||||
return Err(RenderError::Unsupported);
|
||||
};
|
||||
let index = participant(&mut people, id)?;
|
||||
if people[index].2 {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
people[index].1 = if line.starts_with("actor ") {
|
||||
format!("{label} (actor)")
|
||||
} else {
|
||||
label.to_owned()
|
||||
};
|
||||
people[index].2 = true;
|
||||
continue;
|
||||
}
|
||||
let event = if line == "end" {
|
||||
blocks.pop().ok_or(RenderError::Unsupported)?;
|
||||
Event::Close
|
||||
} else if let Some(text) = line.strip_prefix("else ") {
|
||||
let Some(("alt", branched)) = blocks.last_mut() else {
|
||||
return Err(RenderError::Unsupported);
|
||||
};
|
||||
if *branched {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
*branched = true;
|
||||
check_label(text)?;
|
||||
Event::Branch(format!("else {text}"))
|
||||
} else if let Some((kind @ ("loop" | "alt" | "opt" | "critical" | "break"), text)) =
|
||||
line.split_once(' ')
|
||||
{
|
||||
check_label(text)?;
|
||||
if blocks.len() == 4 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
blocks.push((kind, false));
|
||||
Event::Open(format!("{kind} {text}"))
|
||||
} else if let Some(after) = line
|
||||
.strip_prefix("Note over ")
|
||||
.or_else(|| line.strip_prefix("note over "))
|
||||
{
|
||||
rest = after;
|
||||
let left = participant(&mut people, identifier(&mut rest)?)?;
|
||||
let right = if let Some(after) = rest.trim_start().strip_prefix(',') {
|
||||
rest = after;
|
||||
participant(&mut people, identifier(&mut rest)?)?
|
||||
} else {
|
||||
left
|
||||
};
|
||||
let text = rest
|
||||
.trim_start()
|
||||
.strip_prefix(':')
|
||||
.ok_or(RenderError::Unsupported)?
|
||||
.trim();
|
||||
check_label(text)?;
|
||||
Event::Note {
|
||||
left: left.min(right),
|
||||
right: left.max(right),
|
||||
text: text.to_owned(),
|
||||
}
|
||||
} else {
|
||||
let from = participant(&mut people, identifier(&mut rest)?)?;
|
||||
rest = rest.trim_start();
|
||||
let mut operator = None;
|
||||
for (token, dashed, arrow) in [
|
||||
("-->>", true, '▶'),
|
||||
("->>", false, '▶'),
|
||||
("-->", true, '┄'),
|
||||
("->", false, '─'),
|
||||
("--x", true, 'x'),
|
||||
("-x", false, 'x'),
|
||||
] {
|
||||
if let Some(after) = rest.strip_prefix(token) {
|
||||
rest = after;
|
||||
operator = Some((dashed, arrow));
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (dashed, arrow) = operator.ok_or(RenderError::Unsupported)?;
|
||||
let to = participant(&mut people, identifier(&mut rest)?)?;
|
||||
let text = rest
|
||||
.trim_start()
|
||||
.strip_prefix(':')
|
||||
.ok_or(RenderError::Unsupported)?
|
||||
.trim();
|
||||
check_label(text)?;
|
||||
Event::Message {
|
||||
from,
|
||||
to,
|
||||
text: text.to_owned(),
|
||||
dashed,
|
||||
arrow,
|
||||
}
|
||||
};
|
||||
if events.len() == 64 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
events.push(event);
|
||||
}
|
||||
if !blocks.is_empty() || people.is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let name_width = people
|
||||
.iter()
|
||||
.map(|(_, label, _)| label.width())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let text_width = events
|
||||
.iter()
|
||||
.map(|event| match event {
|
||||
Event::Message { text, .. } | Event::Open(text) | Event::Branch(text) => text.width(),
|
||||
Event::Note { text, .. } => text.width() + 6,
|
||||
Event::Close => 0,
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let box_width = name_width + 4;
|
||||
let stride = (box_width + 2).max(text_width + 4);
|
||||
// Four frame levels consume eight columns on each side, separate from participant lifelines.
|
||||
let centers = (0..people.len())
|
||||
.map(|i| 10 + box_width / 2 + stride * i)
|
||||
.collect::<Vec<_>>();
|
||||
let last = centers[people.len() - 1];
|
||||
let width = (last + box_width - box_width / 2 + 10).max(last + text_width + 14);
|
||||
if width * (3 + 4 * events.len()) > super::MAX_CELLS {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
let mut rows = vec![vec![Cell::edge(' '); width]; 3];
|
||||
for (i, (_, name, _)) in people.iter().enumerate() {
|
||||
let left = centers[i] - box_width / 2;
|
||||
let right = left + box_width - 1;
|
||||
rows[0][left] = Cell::node('┌');
|
||||
rows[0][right] = Cell::node('┐');
|
||||
rows[2][left] = Cell::node('└');
|
||||
rows[2][right] = Cell::node('┘');
|
||||
rows[0][left + 1..right].fill(Cell::node('─'));
|
||||
rows[2][left + 1..right].fill(Cell::node('─'));
|
||||
rows[1][left] = Cell::node('│');
|
||||
rows[1][right] = Cell::node('│');
|
||||
put_text(&mut rows[1], left + 2, name)?;
|
||||
}
|
||||
let mut depth = 0;
|
||||
for event in events {
|
||||
let count = if matches!(event, Event::Message { from, to, .. } if from == to) {
|
||||
4
|
||||
} else {
|
||||
3
|
||||
};
|
||||
let top = rows.len();
|
||||
rows.extend((0..count).map(|_| {
|
||||
let mut row = vec![Cell::edge(' '); width];
|
||||
for x in ¢ers {
|
||||
row[*x] = Cell::edge('│');
|
||||
}
|
||||
for level in 0..depth {
|
||||
row[level * 2] = Cell::node('│');
|
||||
row[width - 1 - level * 2] = Cell::node('│');
|
||||
}
|
||||
row
|
||||
}));
|
||||
match event {
|
||||
Event::Message {
|
||||
from,
|
||||
to,
|
||||
text,
|
||||
dashed,
|
||||
arrow,
|
||||
} => {
|
||||
let (a, b) = (centers[from], centers[to]);
|
||||
let arrow = if a >= b && arrow == '▶' {
|
||||
'◀'
|
||||
} else {
|
||||
arrow
|
||||
};
|
||||
let stroke = if dashed { '┄' } else { '─' };
|
||||
put_text(&mut rows[top], a.min(b) + 2, &text)?;
|
||||
if a == b {
|
||||
rows[top + 1][a..a + 4].fill(Cell::edge(stroke));
|
||||
rows[top + 1][a] = Cell::edge('├');
|
||||
rows[top + 1][a + 4] = Cell::edge('┐');
|
||||
rows[top + 2][a..a + 4].fill(Cell::edge(stroke));
|
||||
rows[top + 2][a + 4] = Cell::edge('┘');
|
||||
rows[top + 2][a] = Cell::edge(arrow);
|
||||
} else {
|
||||
rows[top + 1][a.min(b)..=a.max(b)].fill(Cell::edge(stroke));
|
||||
for x in ¢ers {
|
||||
if *x > a.min(b) && *x < a.max(b) {
|
||||
rows[top + 1][*x] = Cell::edge('┼');
|
||||
}
|
||||
}
|
||||
rows[top + 1][a] = Cell::edge(if a < b { '├' } else { '┤' });
|
||||
rows[top + 1][b] = Cell::edge(arrow);
|
||||
}
|
||||
}
|
||||
Event::Note { left, right, text } => {
|
||||
let label = format!("Note: {text}");
|
||||
let start = centers[left];
|
||||
let end = centers[right].max(start + label.width() + 3);
|
||||
rows[top][start..=end].fill(Cell::node('─'));
|
||||
rows[top + 2][start..=end].fill(Cell::node('─'));
|
||||
rows[top][start] = Cell::node('┌');
|
||||
rows[top][end] = Cell::node('┐');
|
||||
rows[top + 2][start] = Cell::node('└');
|
||||
rows[top + 2][end] = Cell::node('┘');
|
||||
rows[top + 1][start..=end].fill(Cell::node(' '));
|
||||
rows[top + 1][start] = Cell::node('│');
|
||||
rows[top + 1][end] = Cell::node('│');
|
||||
put_text(&mut rows[top + 1], start + 2, &label)?;
|
||||
}
|
||||
Event::Open(label) | Event::Branch(label) => {
|
||||
let opening = !label.starts_with("else ");
|
||||
if opening {
|
||||
depth += 1;
|
||||
}
|
||||
let left = (depth - 1) * 2;
|
||||
let right = width - 1 - left;
|
||||
rows[top][left..=right].fill(Cell::node('─'));
|
||||
rows[top][left] = Cell::node(if opening { '┌' } else { '├' });
|
||||
rows[top][right] = Cell::node(if opening { '┐' } else { '┤' });
|
||||
put_text(&mut rows[top], left + 2, &label)?;
|
||||
for row in &mut rows[top + 1..top + 3] {
|
||||
row[left] = Cell::node('│');
|
||||
row[right] = Cell::node('│');
|
||||
}
|
||||
}
|
||||
Event::Close => {
|
||||
depth -= 1;
|
||||
let left = depth * 2;
|
||||
let right = width - 1 - left;
|
||||
rows[top][left..=right].fill(Cell::node('─'));
|
||||
rows[top][left] = Cell::node('└');
|
||||
rows[top][right] = Cell::node('┘');
|
||||
for row in &mut rows[top + 1..top + 3] {
|
||||
row[left] = Cell::node(' ');
|
||||
row[right] = Cell::node(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if rows.iter().any(|row| {
|
||||
row.iter()
|
||||
.rposition(|cell| cell.symbol != ' ')
|
||||
.is_some_and(|x| x >= max_width)
|
||||
}) {
|
||||
return Err(RenderError::TooWide);
|
||||
}
|
||||
Ok(finish(rows))
|
||||
}
|
||||
|
||||
fn participant(people: &mut Vec<(String, String, bool)>, id: &str) -> Result<usize, RenderError> {
|
||||
if let Some(index) = people.iter().position(|(name, _, _)| name == id) {
|
||||
return Ok(index);
|
||||
}
|
||||
if people.len() == 8 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
people.push((id.to_owned(), id.to_owned(), false));
|
||||
Ok(people.len() - 1)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
source: mermaid/src/tests.rs
|
||||
expression: "render(source, 100).unwrap()"
|
||||
---
|
||||
┌───────────────┐
|
||||
│ Go []; & │
|
||||
│ ├────────┐
|
||||
└───────────────┘ │
|
||||
│
|
||||
│
|
||||
┌───────────────┐ │
|
||||
│ ◇ x < 3? │ │
|
||||
│ ├◄───────┘
|
||||
│ ├──y|n─────┐
|
||||
│ ├──no──────╪─┐
|
||||
└───────────────┘ │ │
|
||||
│ │
|
||||
│ │
|
||||
┌───────────────┐ │ │
|
||||
│ Reserve │ │ │
|
||||
│ ├◄─────────┘ │
|
||||
│ ├────────────╪─┐
|
||||
└───────────────┘ │ │
|
||||
│ │
|
||||
│ │
|
||||
┌───────────────┐ │ │
|
||||
│ Waitlist │ │ │
|
||||
│ ├◄───────────┘ │
|
||||
│ ├──────────────╪───────┐
|
||||
└───────────────┘ │ │
|
||||
│ │
|
||||
│ │
|
||||
┌───────────────┐ │ │
|
||||
│ ◇ Paid? │ │ │
|
||||
│ ├◄─────────────┘ │
|
||||
│ ├──yes───────────┐ │
|
||||
│ ├──no────────────╪─┐ │
|
||||
│ ├◄───────────────╪─╪─┐ │
|
||||
└───────────────┘ │ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
┌───────────────┐ │ │ │ │
|
||||
│ Ship │ │ │ │ │
|
||||
│ ├◄───────────────┘ │ │ │
|
||||
│ ├──────────────────╪─╪─╪─┐
|
||||
└───────────────┘ │ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
┌───────────────┐ │ │ │ │
|
||||
│ Retry payment │ │ │ │ │
|
||||
│ ├◄─────────────────┘ │ │ │
|
||||
│ ├────────────────────┘ │ │
|
||||
└───────────────┘ │ │
|
||||
│ │
|
||||
│ │
|
||||
┌───────────────┐ │ │
|
||||
│ Notify buyer │ │ │
|
||||
│ ├◄─────────────────────┘ │
|
||||
│ ├◄───────────────────────┘
|
||||
└───────────────┘
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: mermaid/src/families_tests.rs
|
||||
assertion_line: 125
|
||||
expression: output
|
||||
---
|
||||
┌──────────────┐ ┌─────────────────────┐ ┌─────────┐
|
||||
│ 请求 │ │ ◇ Réponse? │ │ Ship 🚀 │
|
||||
└┬──────┬──────┘ └┬──────┬──────┬──────┘ └┬────────┘
|
||||
│ ▲ ▲ │ │ ▲
|
||||
│准备 │ │ │retry │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ │ │ │
|
||||
└──────╪──────────┘ │ │ │
|
||||
│ │ │ │
|
||||
└─────────────────┘ │ │
|
||||
│ │
|
||||
└──────────┘
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
source: mermaid/src/families_tests.rs
|
||||
expression: output
|
||||
---
|
||||
┌──────────────────┐
|
||||
│ order │
|
||||
│ ───── │
|
||||
│ +int[] ids │
|
||||
│ +String a;b │
|
||||
│ +submit() │
|
||||
│ +cancel() │
|
||||
│ ├◆─(1) contains────┐
|
||||
│ ├──(1) pays with───╪─┐
|
||||
│ ├─┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╪┄╪┄┄┄┐
|
||||
└──────────────────┘ │ │ ┆
|
||||
│ │ ┆
|
||||
│ │ ┆
|
||||
┌──────────────────┐ │ │ ┆
|
||||
│ LineItem │ │ │ ┆
|
||||
│ ──────── │ │ │ ┆
|
||||
│ +int quantity │ │ │ ┆
|
||||
│ +Decimal price │ │ │ ┆
|
||||
│ +subtotal() │ │ │ ┆
|
||||
│ ├──(1..*)──────────┘ │ ┆
|
||||
└──────────────────┘ │ ┆
|
||||
│ ┆
|
||||
│ ┆
|
||||
┌──────────────────┐ │ ┆
|
||||
│ Payment │ │ ┆
|
||||
│ ─────── │ │ ┆
|
||||
│ +Decimal amount │ │ ┆
|
||||
│ +authorize() │ │ ┆
|
||||
│ ├◄─(1)───────────────┘ ┆
|
||||
│ ├◁─────────────────────┐ ┆
|
||||
└──────────────────┘ │ ┆
|
||||
│ ┆
|
||||
│ ┆
|
||||
┌──────────────────┐ │ ┆
|
||||
│ CardPayment │ │ ┆
|
||||
│ ─────────── │ │ ┆
|
||||
│ +String lastFour │ │ ┆
|
||||
│ +authorize() │ │ ┆
|
||||
│ ├──────────────────────┘ ┆
|
||||
│ ├─┄updates┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
└──────────────────┘
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
source: mermaid/src/families_tests.rs
|
||||
assertion_line: 107
|
||||
expression: output
|
||||
---
|
||||
┌─────────────────────────────────┐
|
||||
│ CUSTOMER │
|
||||
│ ──────── │
|
||||
│ int id PK │
|
||||
│ string email UK │
|
||||
│ string name │
|
||||
│ ├──(1) places───────┐
|
||||
└─────────────────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────────────────┐ │
|
||||
│ ORDER │ │
|
||||
│ ───── │ │
|
||||
│ int id PK │ │
|
||||
│ int customer_id FK │ │
|
||||
│ string status │ │
|
||||
│ ├──(0..many)────────┘
|
||||
│ ├──(1) contains───────┐
|
||||
└─────────────────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────────────────┐ │
|
||||
│ LINE_ITEM │ │
|
||||
│ ───────── │ │
|
||||
│ int order_id PK, FK — order key │ │
|
||||
│ int product_id PK, FK │ │
|
||||
│ int quantity │ │
|
||||
│ ├──(1..many)──────────┘
|
||||
│ ├─┄(0..many)┄┄┄┄┄┄┄┄┄┄┄┄┐
|
||||
└─────────────────────────────────┘ ┆
|
||||
┆
|
||||
┆
|
||||
┌─────────────────────────────────┐ ┆
|
||||
│ PRODUCT │ ┆
|
||||
│ ─────── │ ┆
|
||||
│ int id PK │ ┆
|
||||
│ string name │ ┆
|
||||
│ decimal price │ ┆
|
||||
│ ├─┄(1) appears_in┄┄┄┄┄┄┄┘
|
||||
└─────────────────────────────────┘
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
source: mermaid/src/families_tests.rs
|
||||
expression: output
|
||||
---
|
||||
┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
|
||||
│ Buyer (actor) │ │ API │ │ 库存 │ │ Payments │
|
||||
└───────────────┘ └───────────────┘ └───────────────┘ └───────────────┘
|
||||
│ data[0] = {x: 1} │ │ │
|
||||
├─────────────────────────▶ │ │
|
||||
│ │ │ │
|
||||
│ │ Reserve items │ │
|
||||
│ ├─────────────────────────▶ │
|
||||
│ │ │ │
|
||||
│ │ say "hello" | C:\tmp │ │
|
||||
│ ◀┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┤ │
|
||||
│ │ │ │
|
||||
┌─opt Items reserved───────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ │ │ │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ ┌─loop Up to 3 attempts────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ │ │ Charge card │ │ │ │
|
||||
│ │ │ ├─────────────────────────┼─────────────────────────▶ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ │ Check fraud │ │
|
||||
│ │ │ │ │ ├───┐ │ │
|
||||
│ │ │ │ │ ◀───┘ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ │ │ Payment status │ │ │ │
|
||||
│ │ │ ◀┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┤ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ ┌─alt Approved─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ │ │ ┌───────────────────────────────────────────────────┐ │ │ │
|
||||
│ │ │ │ │ Note: Payment recorded │ │ │ │
|
||||
│ │ │ │ └───────────────────────────────────────────────────┘ │ │ │
|
||||
│ │ │ │ Order confirmed │ │ │ │ │ │
|
||||
│ │ │ ◀┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┤ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ ├─else Declined────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ Release items │ │ │ │ │
|
||||
│ │ │ │ ├─────────────────────────▶ │ │ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ │ │ Payment failed │ │ │ │ │ │
|
||||
│ │ │ ◀┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┤ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │ │ │
|
||||
│ │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ │ │ │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
source: mermaid/src/families_tests.rs
|
||||
expression: output
|
||||
---
|
||||
┌─────────────────────┐
|
||||
│ Payment pending │
|
||||
│ ─────────────── │
|
||||
│ Retry up to 3 times │
|
||||
│ ├◄────────────────┐
|
||||
│ ├──paid───────────╪───┐
|
||||
│ ├──declined───────╪───╪─┐
|
||||
└─────────────────────┘ │ │ │
|
||||
│ │ │
|
||||
│ │ │
|
||||
┌─────────────────────┐ │ │ │
|
||||
│ ● initial │ │ │ │
|
||||
│ ├─────────────┐ │ │ │
|
||||
└─────────────────────┘ │ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
┌─────────────────────┐ │ │ │ │
|
||||
│ Order drafted │ │ │ │ │
|
||||
│ ───────────── │ │ │ │ │
|
||||
│ Awaiting submission │ │ │ │ │
|
||||
│ ├◄────────────┘ │ │ │
|
||||
│ ├──submit───────┐ │ │ │
|
||||
│ ├◄──────────────╪─╪───╪─╪───────┐
|
||||
└─────────────────────┘ │ │ │ │ │
|
||||
│ │ │ │ │
|
||||
│ │ │ │ │
|
||||
┌─────────────────────┐ │ │ │ │ │
|
||||
│ Validating │ │ │ │ │ │
|
||||
│ ├◄──────────────┘ │ │ │ │
|
||||
│ ├──[ready]────────┘ │ │ │
|
||||
│ ├──invalid──────────┐ │ │ │
|
||||
└─────────────────────┘ │ │ │ │
|
||||
│ │ │ │
|
||||
│ │ │ │
|
||||
┌─────────────────────┐ │ │ │ │
|
||||
│ Rejected │ │ │ │ │
|
||||
│ ├◄──────────────────┘ │ │ │
|
||||
│ ├◄────────────────────╪─┘ │
|
||||
│ ├──revise─────────────╪─────────┘
|
||||
└─────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────┐ │
|
||||
│ Packing │ │
|
||||
│ ├◄────────────────────┘
|
||||
│ ├──dispatch───────────────┐
|
||||
└─────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────┐ │
|
||||
│ Shipped │ │
|
||||
│ ├◄────────────────────────┘
|
||||
│ ├──received─────────────────┐
|
||||
└─────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────┐ │
|
||||
│ Delivered │ │
|
||||
│ ├◄──────────────────────────┘
|
||||
│ ├─────────────────────────────┐
|
||||
└─────────────────────┘ │
|
||||
│
|
||||
│
|
||||
┌─────────────────────┐ │
|
||||
│ ◎ final │ │
|
||||
│ ├◄────────────────────────────┘
|
||||
└─────────────────────┘
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
source: mermaid/src/tests.rs
|
||||
assertion_line: 36
|
||||
expression: "cases.join(\"\\n\\n\")"
|
||||
---
|
||||
TD
|
||||
╭─────────╮
|
||||
│ 请求 │
|
||||
│ Ready │
|
||||
│ ├──go───┐
|
||||
│ ├──go───╪─┐
|
||||
│ ├◄──────╪─╪───┐
|
||||
│ ├───────╪─╪───╪─┐
|
||||
│ ├◄┄┄┄┄┄┄╪┄╪┄┄┄╪┄╪┄┄┄┐
|
||||
╰─────────╯ │ │ │ │ ┆
|
||||
│ │ │ │ ┆
|
||||
│ │ │ │ ┆
|
||||
┌─────────┐ │ │ │ │ ┆
|
||||
│ Work │ │ │ │ │ ┆
|
||||
│ next │ │ │ │ │ ┆
|
||||
│ ├◄──────┘ │ │ │ ┆
|
||||
│ ├─┄no┄┄┄┄┄╪┄┐ │ │ ┆
|
||||
│ ├─────────╪─╪─╪─┘ ┆
|
||||
│ ├─┄┄┄┄┄┄┄┄╪┄╪┄╪┄┄┄┐ ┆
|
||||
│ ├◄┄┄┄┄┄┄┄┄╪┄╪┄╪┄┄┄╪┄┘
|
||||
└─────────┘ │ ┆ │ ┆
|
||||
│ ┆ │ ┆
|
||||
│ ┆ │ ┆
|
||||
┌─────────┐ │ ┆ │ ┆
|
||||
│ ◇ Done? │ │ ┆ │ ┆
|
||||
│ Retry? │ │ ┆ │ ┆
|
||||
│ ├◄────────┘ ┆ │ ┆
|
||||
│ ├◄┄┄┄┄┄┄┄┄┄┄┘ │ ┆
|
||||
│ ├◄────────────┘ ┆
|
||||
│ ├─┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
└─────────┘
|
||||
|
||||
BT
|
||||
┌─────────┐
|
||||
│ ◇ Done? │
|
||||
│ Retry? │
|
||||
│ ├◄────────┐
|
||||
│ ├◄┄┄┄┄┄┄┄┄╪┄┐
|
||||
│ ├◄────────╪─╪─┐
|
||||
│ ├─┄┄┄┄┄┄┄┄╪┄╪┄╪┄┄┄┐
|
||||
└─────────┘ │ ┆ │ ┆
|
||||
│ ┆ │ ┆
|
||||
│ ┆ │ ┆
|
||||
┌─────────┐ │ ┆ │ ┆
|
||||
│ Work │ │ ┆ │ ┆
|
||||
│ next │ │ ┆ │ ┆
|
||||
│ ├◄──────┐ │ ┆ │ ┆
|
||||
│ ├─┄no┄┄┄╪┄╪┄┘ │ ┆
|
||||
│ ├───────╪─╪───╪─┐ ┆
|
||||
│ ├─┄┄┄┄┄┄╪┄╪┄┄┄╪┄╪┄┘
|
||||
│ ├◄┄┄┄┄┄┄╪┄╪┄┄┄╪┄╪┄┄┄┐
|
||||
└─────────┘ │ │ │ │ ┆
|
||||
│ │ │ │ ┆
|
||||
│ │ │ │ ┆
|
||||
╭─────────╮ │ │ │ │ ┆
|
||||
│ 请求 │ │ │ │ │ ┆
|
||||
│ Ready │ │ │ │ │ ┆
|
||||
│ ├──go───┘ │ │ │ ┆
|
||||
│ ├──go─────┘ │ │ ┆
|
||||
│ ├◄────────────┘ │ ┆
|
||||
│ ├───────────────┘ ┆
|
||||
│ ├◄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
╰─────────╯
|
||||
|
||||
LR
|
||||
╭────────────────────╮ ┌────────────────────┐ ┌────────────────┐
|
||||
│ 请求 │ │ Work │ │ ◇ Done? │
|
||||
│ Ready │ │ next │ │ Retry? │
|
||||
╰┬───┬───┬───┬───┬───╯ └┬───┬───┬───┬───┬───┘ └┬───┬───┬───┬───┘
|
||||
│ │ ▲ │ ▲ ▲ │ │ │ ▲ ▲ ▲ ▲ │
|
||||
│go │go │ │ ┆ │ ┆no │ ┆ ┆ │ ┆ │ ┆
|
||||
│ │ │ │ ┆ │ ┆ │ ┆ ┆ │ ┆ │ ┆
|
||||
│ │ │ │ ┆ │ ┆ │ ┆ ┆ │ ┆ │ ┆
|
||||
└───╪───╪───╪───╪───────┘ ┆ │ ┆ ┆ │ ┆ │ ┆
|
||||
│ │ │ ┆ ┆ │ ┆ ┆ │ ┆ │ ┆
|
||||
└───╪───╪───╪───────────╪───╪───╪───╪───────┘ ┆ │ ┆
|
||||
│ │ ┆ ┆ │ ┆ ┆ ┆ │ ┆
|
||||
│ │ ┆ └┄┄┄╪┄┄┄╪┄┄┄╪┄┄┄┄┄┄┄┄┄┄┄┘ │ ┆
|
||||
│ │ ┆ │ ┆ ┆ │ ┆
|
||||
└───╪───╪───────────────╪───╪───╪───────────────┘ ┆
|
||||
│ ┆ │ ┆ ┆ ┆
|
||||
└───╪───────────────┘ ┆ ┆ ┆
|
||||
┆ ┆ ┆ ┆
|
||||
┆ └┄┄┄╪┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
┆ ┆
|
||||
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
|
||||
RL
|
||||
┌────────────────┐ ┌────────────────────┐ ╭────────────────────╮
|
||||
│ ◇ Done? │ │ Work │ │ 请求 │
|
||||
│ Retry? │ │ next │ │ Ready │
|
||||
└┬───┬───┬───┬───┘ └┬───┬───┬───┬───┬───┘ ╰┬───┬───┬───┬───┬───╯
|
||||
▲ ▲ ▲ │ ▲ │ │ │ ▲ │ │ ▲ │ ▲
|
||||
│ ┆ │ ┆ │ ┆no │ ┆ ┆ │go │go │ │ ┆
|
||||
│ ┆ │ ┆ │ ┆ │ ┆ ┆ │ │ │ │ ┆
|
||||
│ ┆ │ ┆ │ ┆ │ ┆ ┆ │ │ │ │ ┆
|
||||
│ ┆ │ ┆ └───╪───╪───╪───╪───────┘ │ │ │ ┆
|
||||
│ ┆ │ ┆ ┆ │ ┆ ┆ │ │ │ ┆
|
||||
└───╪───╪───╪───────────╪───╪───╪───╪───────────┘ │ │ ┆
|
||||
┆ │ ┆ ┆ │ ┆ ┆ │ │ ┆
|
||||
└┄┄┄╪┄┄┄╪┄┄┄┄┄┄┄┄┄┄┄┘ │ ┆ ┆ │ │ ┆
|
||||
│ ┆ │ ┆ ┆ │ │ ┆
|
||||
└───╪───────────────╪───╪───╪───────────────┘ │ ┆
|
||||
┆ │ ┆ ┆ │ ┆
|
||||
┆ └───╪───╪───────────────────┘ ┆
|
||||
┆ ┆ ┆ ┆
|
||||
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘ ┆ ┆
|
||||
┆ ┆
|
||||
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
|
||||
119
codex-rs/mermaid/src/state.rs
Normal file
119
codex-rs/mermaid/src/state.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Flat state machines, with distinct initial/final pseudostates and labeled transitions.
|
||||
//! Aliases and descriptions accumulate in source order: first the title, then body rows.
|
||||
|
||||
use super::Direction;
|
||||
use super::Edge;
|
||||
use super::Graph;
|
||||
use super::MAX_EDGES;
|
||||
use super::RenderError;
|
||||
use super::parse::check_label;
|
||||
use super::parse::identifier;
|
||||
|
||||
pub(super) fn parse(body: &[&str]) -> Result<Graph, RenderError> {
|
||||
let mut graph = Graph::default();
|
||||
let mut direction = false;
|
||||
for &line in body {
|
||||
if matches!(line, "state" | "direction" | "note" | "end" | "hide") {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("direction ") {
|
||||
if direction {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
graph.direction = Direction::parse(value.trim())?;
|
||||
direction = true;
|
||||
continue;
|
||||
}
|
||||
let mut rest = line;
|
||||
if let Some(after) = rest.strip_prefix("state \"") {
|
||||
let (label, after) = after.split_once('"').ok_or(RenderError::Unsupported)?;
|
||||
check_label(label)?;
|
||||
rest = after
|
||||
.trim_start()
|
||||
.strip_prefix("as ")
|
||||
.ok_or(RenderError::Unsupported)?;
|
||||
let index = graph.node(identifier(&mut rest)?)?;
|
||||
if !rest.trim().is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
add_description(&mut graph.nodes[index], label)?;
|
||||
continue;
|
||||
}
|
||||
let from = if let Some(after) = rest.strip_prefix("[*]") {
|
||||
rest = after;
|
||||
let index = graph.node("[initial]")?;
|
||||
graph.nodes[index].label = "● initial".to_owned();
|
||||
index
|
||||
} else {
|
||||
let id = identifier(&mut rest)?;
|
||||
if (id.eq_ignore_ascii_case("accTitle") || id.eq_ignore_ascii_case("accDescr"))
|
||||
&& rest.trim_start().starts_with(':')
|
||||
{
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
graph.node(id)?
|
||||
};
|
||||
rest = rest.trim();
|
||||
if rest.is_empty() && graph.nodes[from].id != "[initial]" {
|
||||
continue;
|
||||
}
|
||||
if let Some(description) = rest
|
||||
.strip_prefix(':')
|
||||
.filter(|text| !text.starts_with("::"))
|
||||
{
|
||||
if graph.nodes[from].id == "[initial]" {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
let description = description.trim();
|
||||
check_label(description)?;
|
||||
add_description(&mut graph.nodes[from], description)?;
|
||||
continue;
|
||||
}
|
||||
rest = rest
|
||||
.strip_prefix("-->")
|
||||
.ok_or(RenderError::Unsupported)?
|
||||
.trim_start();
|
||||
let to = if let Some(after) = rest.strip_prefix("[*]") {
|
||||
rest = after;
|
||||
let index = graph.node("[final]")?;
|
||||
graph.nodes[index].label = "◎ final".to_owned();
|
||||
index
|
||||
} else {
|
||||
graph.node(identifier(&mut rest)?)?
|
||||
};
|
||||
let label = if let Some(label) = rest
|
||||
.trim()
|
||||
.strip_prefix(':')
|
||||
.filter(|text| !text.starts_with("::"))
|
||||
{
|
||||
let label = label.trim();
|
||||
check_label(label)?;
|
||||
label.to_owned()
|
||||
} else if rest.trim().is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
return Err(RenderError::Unsupported);
|
||||
};
|
||||
if graph.edges.len() == MAX_EDGES {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
graph.edges.push(Edge::directed(from, to, label));
|
||||
}
|
||||
if graph.nodes.is_empty() {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn add_description(node: &mut super::Node, description: &str) -> Result<(), RenderError> {
|
||||
if !node.declared {
|
||||
node.label = description.to_owned();
|
||||
node.declared = true;
|
||||
} else {
|
||||
if node.members.len() == 16 {
|
||||
return Err(RenderError::Limit);
|
||||
}
|
||||
node.members.push(description.to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
101
codex-rs/mermaid/src/syntax.rs
Normal file
101
codex-rs/mermaid/src/syntax.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Small lexical boundaries shared by the family parsers; no decoding or multiline labels.
|
||||
//! Source limits are enforced before scanning, and undecoded entities always fail intact.
|
||||
|
||||
use super::RenderError;
|
||||
|
||||
/// Split statements using family-specific quote and member rules. Sequence quotes are literal;
|
||||
/// class bodies consume member lines whole. Flowchart label delimiters and other quoted tokens
|
||||
/// protect semicolons, except in colon-delimited class/state text, where quotes are literal too.
|
||||
pub(super) fn statements(source: &str) -> Result<Vec<&str>, RenderError> {
|
||||
let mut result = Vec::new();
|
||||
let mut class_body = false;
|
||||
for line in source.lines() {
|
||||
let mut rest = line.trim();
|
||||
if rest.starts_with("%%{") {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
if rest.starts_with("%%") {
|
||||
continue;
|
||||
}
|
||||
// Mermaid #name;/#number; and HTML &name;/&#number; need decoding. Reject before
|
||||
// statement splitting can discard the semicolon and turn them into literal text.
|
||||
if rest.match_indices(['#', '&']).any(|(index, _)| {
|
||||
let after = &rest[index + 1..];
|
||||
let len = after
|
||||
.bytes()
|
||||
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
|
||||
.count();
|
||||
len > 0 && after[len..].starts_with(';')
|
||||
}) {
|
||||
return Err(RenderError::Unsupported);
|
||||
}
|
||||
while !rest.is_empty() {
|
||||
let header = result.first().copied().unwrap_or("");
|
||||
if header == "classDiagram"
|
||||
&& (class_body
|
||||
|| rest.starts_with("class ")
|
||||
&& rest
|
||||
.split_once('{')
|
||||
.is_some_and(|(declaration, _)| !declaration.contains(';')))
|
||||
{
|
||||
// Compact bodies are not supported here; let the class parser reject them.
|
||||
class_body = rest != "}";
|
||||
result.push(rest);
|
||||
break;
|
||||
}
|
||||
let colon_text = matches!(header, "classDiagram" | "stateDiagram" | "stateDiagram-v2");
|
||||
let flowchart = matches!(
|
||||
header.split_whitespace().next(),
|
||||
Some("flowchart" | "graph")
|
||||
);
|
||||
let mut close = None;
|
||||
let mut quoted = false;
|
||||
let mut literal = header == "sequenceDiagram";
|
||||
let end = rest.char_indices().find_map(|(index, ch)| {
|
||||
match ch {
|
||||
'"' if !literal => quoted = !quoted,
|
||||
':' if colon_text && !quoted => literal = true,
|
||||
';' if !quoted && close.is_none() => return Some(index),
|
||||
ch if flowchart && !quoted => {
|
||||
close = match (close, ch) {
|
||||
(Some(end), ch) if end == ch => None,
|
||||
(None, '[') => Some(']'),
|
||||
(None, '{') => Some('}'),
|
||||
(None, '|') => Some('|'),
|
||||
(close, _) => close,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
});
|
||||
let (statement, remaining) = match end {
|
||||
Some(end) => (&rest[..end], &rest[end + 1..]),
|
||||
None => (rest, ""),
|
||||
};
|
||||
if !statement.trim().is_empty() {
|
||||
result.push(statement.trim());
|
||||
}
|
||||
rest = remaining.trim();
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Consume a flowchart label up to its closing delimiter, protecting delimiters inside a leading
|
||||
/// quoted token. Returns the raw label (including quotes) and untouched remaining syntax.
|
||||
/// Quotes do not use backslash escaping in Mermaid; entities remain unsupported.
|
||||
pub(super) fn delimited_label<'a>(
|
||||
text: &'a str,
|
||||
close: &str,
|
||||
) -> Result<(&'a str, &'a str), RenderError> {
|
||||
if let Some(quoted) = text.strip_prefix('"') {
|
||||
let end = quoted.find('"').ok_or(RenderError::Unsupported)? + 2;
|
||||
let rest = text[end..]
|
||||
.strip_prefix(close)
|
||||
.ok_or(RenderError::Unsupported)?;
|
||||
Ok((&text[..end], rest))
|
||||
} else {
|
||||
text.split_once(close).ok_or(RenderError::Unsupported)
|
||||
}
|
||||
}
|
||||
453
codex-rs/mermaid/src/tests.rs
Normal file
453
codex-rs/mermaid/src/tests.rs
Normal file
@@ -0,0 +1,453 @@
|
||||
use super::RenderError;
|
||||
use super::render;
|
||||
use insta::assert_snapshot;
|
||||
use pretty_assertions::assert_eq;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
#[test]
|
||||
fn stadium_declarations_and_references() {
|
||||
let graph =
|
||||
super::parse::parse("flowchart TD", &["A", "A([Ready?])", "A", "A([Ready?])"]).unwrap();
|
||||
assert_eq!(
|
||||
graph.nodes,
|
||||
vec![super::Node {
|
||||
id: "A".to_owned(),
|
||||
label: "Ready?".to_owned(),
|
||||
shape: super::Shape::Stadium,
|
||||
declared: true,
|
||||
members: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stadiums_with_other_shapes_in_every_direction() {
|
||||
let mut cases = Vec::new();
|
||||
for direction in ["TD", "BT", "LR", "RL"] {
|
||||
let source = format!(
|
||||
"flowchart {direction}; A([\"请求<br>Ready\"]) -- go --> B[Work<br/>next] & C{{\"Done?<br />Retry?\"}}; B -. no .-> C; C <--> A; B --- A; C -.- B; A <-.-> B"
|
||||
);
|
||||
let output = render(&source, /*max_width*/ 100).unwrap();
|
||||
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
||||
assert_eq!(render(&source, width), Ok(output.clone()));
|
||||
assert_eq!(render(&source, width - 1), Err(RenderError::TooWide));
|
||||
cases.push(format!("{direction}\n{output}"));
|
||||
}
|
||||
assert_snapshot!(cases.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_flowchart_forms_preserve_graph() {
|
||||
let quoted = r#"A["Review & confirm;"] -->|"Yes & continue"| B{"Ready?"}
|
||||
B --> C(["Checkout"])
|
||||
A[Review & confirm;]"#;
|
||||
let unquoted = quoted.replace('"', "");
|
||||
assert_eq!(
|
||||
super::parse::parse("flowchart TD", "ed.lines().collect::<Vec<_>>()).unwrap(),
|
||||
super::parse::parse("flowchart TD", &unquoted.lines().collect::<Vec<_>>()).unwrap(),
|
||||
);
|
||||
for (infix, pipe) in [
|
||||
("-- Yes -->", "-->|Yes|"),
|
||||
("-- \"Yes & continue\" -->", "-->|\"Yes & continue\"|"),
|
||||
("-. retry .->", "-.->|retry|"),
|
||||
] {
|
||||
assert_eq!(
|
||||
super::parse::parse("flowchart", &[&format!("A {infix} B --> C")]).unwrap(),
|
||||
super::parse::parse("graph TB", &[&format!("A {pipe} B --> C")]).unwrap(),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
super::parse::parse("graph", &["A[Input & config] & B -- send --> C & D -.-> E"]).unwrap(),
|
||||
super::parse::parse(
|
||||
"flowchart TD",
|
||||
&[
|
||||
"A[Input & config]",
|
||||
"B",
|
||||
"C",
|
||||
"D",
|
||||
"E",
|
||||
"A -->|send| C",
|
||||
"A -->|send| D",
|
||||
"B -->|send| C",
|
||||
"B -->|send| D",
|
||||
"C -.-> E",
|
||||
"D -.-> E",
|
||||
]
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
super::parse::parse("flowchart", &["A--- oB", "A-.- xB"])
|
||||
.unwrap()
|
||||
.nodes,
|
||||
super::parse::parse("flowchart", &["A", "oB", "xB"])
|
||||
.unwrap()
|
||||
.nodes,
|
||||
);
|
||||
assert_eq!(
|
||||
super::parse::parse("flowchart", &["A --> B & B"]).unwrap(),
|
||||
super::parse::parse("flowchart TD", &["A --> B", "A --> B"]).unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
render(&format!("graph TD; {quoted}"), /*max_width*/ 180).unwrap(),
|
||||
render(&format!("graph TD; {unquoted}"), /*max_width*/ 180).unwrap(),
|
||||
);
|
||||
let source = r#"graph TD;A["chimpansen hoppar ()[]"] -->|"x | y; z"| B{"x < 3?"};"#;
|
||||
let statements = super::syntax::statements(source).unwrap();
|
||||
assert_eq!(
|
||||
super::parse::parse(statements[0], &statements[1..]).unwrap(),
|
||||
super::Graph {
|
||||
nodes: vec![
|
||||
super::Node {
|
||||
id: "A".into(),
|
||||
label: "chimpansen hoppar ()[]".into(),
|
||||
shape: super::Shape::Rectangle,
|
||||
declared: true,
|
||||
members: Vec::new(),
|
||||
},
|
||||
super::Node {
|
||||
id: "B".into(),
|
||||
label: "x < 3?".into(),
|
||||
shape: super::Shape::Decision,
|
||||
declared: true,
|
||||
members: Vec::new(),
|
||||
},
|
||||
],
|
||||
edges: vec![super::Edge::directed(
|
||||
/*from*/ 0,
|
||||
/*to*/ 1,
|
||||
"x | y; z".into()
|
||||
)],
|
||||
..super::Graph::default()
|
||||
}
|
||||
);
|
||||
for (quoted, label) in [
|
||||
(r#"A["(Database)"]"#, "(Database)"),
|
||||
(r#"A["/Input/"]"#, "/Input/"),
|
||||
] {
|
||||
let graph = super::parse::parse("flowchart TD", &[quoted]).unwrap();
|
||||
assert_eq!(
|
||||
graph.nodes,
|
||||
vec![super::Node {
|
||||
id: "A".to_owned(),
|
||||
label: label.to_owned(),
|
||||
shape: super::Shape::Rectangle,
|
||||
declared: true,
|
||||
members: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_labels_keep_source_fallback() {
|
||||
for entity in ["&", "&", "&", "#9829;", "#semi;"] {
|
||||
for source in [
|
||||
format!("sequenceDiagram\nA->>B: {entity}"),
|
||||
format!("classDiagram\nclass A {{\n{entity}\n}}"),
|
||||
format!("stateDiagram-v2; A-->B: {entity}"),
|
||||
format!("erDiagram\nA {{\nstring value \"{entity}\"\n}}"),
|
||||
format!("flowchart TD; A[\"{entity}\"]"),
|
||||
format!("flowchart TD; A -->|\"{entity}\"| B"),
|
||||
] {
|
||||
assert_eq!(
|
||||
render(&source, /*max_width*/ 100),
|
||||
Err(RenderError::Unsupported),
|
||||
"{source:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flowchart_ampersands_preserve_statement_separators() {
|
||||
let source = "flowchart TD; A[R&D] -->|R&D| B[Review & confirm]; B --> C";
|
||||
assert_eq!(
|
||||
render(&format!("%% &\n{source}"), /*max_width*/ 100),
|
||||
render(&source.replace(';', "\n"), /*max_width*/ 100),
|
||||
);
|
||||
assert!(
|
||||
render(source, /*max_width*/ 100)
|
||||
.unwrap()
|
||||
.contains("Review & confirm")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_flowchart_labels_reject_malformed_and_unsafe_text() {
|
||||
for label in [
|
||||
"\"unfinished",
|
||||
"unfinished\"",
|
||||
"\"embedded\"quote\"",
|
||||
"\"\"",
|
||||
"\"<b>HTML</b>\"",
|
||||
"\"before <b\"",
|
||||
"\"one<br/><b>two</b>\"",
|
||||
"\"one<br class='x'>two\"",
|
||||
"\"\u{1b}\"",
|
||||
] {
|
||||
for source in [
|
||||
format!("flowchart TD; A[{label}]"),
|
||||
format!("flowchart TD; A -->|{label}| B"),
|
||||
format!("flowchart TD; A -- {label} --> B"),
|
||||
] {
|
||||
assert_eq!(
|
||||
render(&source, /*max_width*/ 100),
|
||||
Err(RenderError::Unsupported),
|
||||
"{source:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branches_merges_and_retry_loop() {
|
||||
let source = "flowchart TD\nA[\"Go []; &\"] --> B{\"x < 3?\"}\nB -->|\"y|n\"| C[Reserve]\nB -->|no| D[Waitlist]\nC --> E{Paid?}\nE -->|yes| F[Ship]\nE -->|no| G[Retry payment]\nG --> E\nD --> H[Notify buyer]\nF --> H";
|
||||
assert_snapshot!(render(source, /*max_width*/ 100).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_partial_or_unsupported_input() {
|
||||
for source in [
|
||||
"flowchart TD; P --> Q; A[(Database)]",
|
||||
"flowchart TD; P --> Q; A[/Input/]",
|
||||
r"flowchart TD; P --> Q; A[\Output\]",
|
||||
r"flowchart TD; P --> Q; A[/Trapezoid\]",
|
||||
r"flowchart TD; P --> Q; A[\Inverse/]",
|
||||
"flowchart TD; P --> Q; A[[Subroutine]]",
|
||||
"flowchart TD; P --> Q; A{{Hexagon}}",
|
||||
r#"flowchart TD; P --> Q; A["`hello **world**`"]"#,
|
||||
r#"flowchart TD; P --> Q; A{"`Decision`"}"#,
|
||||
r#"flowchart TD; P --> Q; A(["`Stadium`"])"#,
|
||||
r#"flowchart TD; P --> Q; A -->|"`Caption`"| B"#,
|
||||
"flowchart TD; subgraph X; A; end",
|
||||
"flowchart TD; A --> B; garbage syntax",
|
||||
"flowchart TD; A --> B &",
|
||||
"flowchart TD; A && B",
|
||||
"flowchart TD; A -- Yes B",
|
||||
"flowchart TD; A -. retry --> B",
|
||||
"flowchart TD; A ==> B",
|
||||
"flowchart TD; A -- hello --- B --> C",
|
||||
"flowchart TD; A -. hello .- B -.-> C",
|
||||
"flowchart TD; A -- hello ----> B",
|
||||
"flowchart TD; A -. hello ..-> B",
|
||||
"flowchart TD; A -- hello o--> B",
|
||||
"flowchart TD; A --oB --> C",
|
||||
"flowchart TD; A -. hello -.-> B",
|
||||
"flowchart TD; A---oB",
|
||||
"flowchart TD; A-.-xB",
|
||||
"flowchart TD; A[one]; A[two]",
|
||||
"flowchart TD; A[<b>HTML</b>]",
|
||||
"flowchart TD; A[]",
|
||||
"flowchart TD; A[\u{1b}]",
|
||||
"flowchart TD; A[e\u{301}]",
|
||||
"flowchart TD; A[👍🏽]",
|
||||
"flowchart TD; A[👩\u{200d}💻]",
|
||||
"flowchart TD; A[✈\u{fe0f}]",
|
||||
"flowchart TD; A[zero\u{200b}width]",
|
||||
"flowchart TD; A[left\u{202e}right]",
|
||||
"flowchart TD; A[\u{2066}isolated\u{2069}]",
|
||||
"flowchart TD; A[unclosed",
|
||||
"flowchart TD; click A",
|
||||
"flowchart TD; A((circle))",
|
||||
"flowchart TD; A(rounded)",
|
||||
"flowchart TD; A([unclosed]",
|
||||
"flowchart TD; A([unclosed)",
|
||||
"flowchart TD; A([label]) trailing",
|
||||
"flowchart TD; A([])",
|
||||
"flowchart TD; A([nested[label]])",
|
||||
"flowchart TD; A([one]); A([two])",
|
||||
"flowchart TD; A([same]); A[same]",
|
||||
"flowchart TD; A{same}; A([same])",
|
||||
"flowchart TD; A -->|unclosed B",
|
||||
"flowchart TD; A[لا]",
|
||||
"flowchart TD; A -->|yes┐| B",
|
||||
"flowchart TD; A -->|one<br/>two| B",
|
||||
"flowchart TD; A -- one<br>two --> B",
|
||||
"flowchart TD; A[<br/><br />]",
|
||||
] {
|
||||
assert_eq!(
|
||||
render(source, /*max_width*/ 100),
|
||||
Err(RenderError::Unsupported),
|
||||
"{source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_graph_and_width_limits() {
|
||||
let grouped = "A & B & C & D --> E & F & G & H & I & J";
|
||||
assert!(render(&format!("graph; {grouped}"), /*max_width*/ 200).is_ok());
|
||||
for source in [
|
||||
" ".repeat(16 * 1024 + 1),
|
||||
format!("graph TD; A[{}]", "x".repeat(41)),
|
||||
format!("graph; A -- {} --> B", "x".repeat(41)),
|
||||
format!("graph; A --> E; {grouped}"),
|
||||
format!("graph; {} --> B", ["A"; 25].join(" & ")),
|
||||
format!("graph TD; A[\"{}\"]", "[]".repeat(21)),
|
||||
format!("graph TD; A([{}])", "x".repeat(41)),
|
||||
format!("graph TD; A[\"ok<br />{}\"]", "界".repeat(21)),
|
||||
format!(
|
||||
"graph TD; {}",
|
||||
(0..17).map(|n| format!("N{n};")).collect::<String>()
|
||||
),
|
||||
format!("graph TD; {}", "A-->B;".repeat(25)),
|
||||
] {
|
||||
assert_eq!(render(&source, /*max_width*/ 200), Err(RenderError::Limit));
|
||||
}
|
||||
let source = format!(
|
||||
"graph LR; A[\"{}<br/>{}\"] --> B[Done]",
|
||||
"界".repeat(20),
|
||||
"x".repeat(40)
|
||||
);
|
||||
let output = render(&source, /*max_width*/ 100).unwrap();
|
||||
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
||||
assert_eq!(render(&source, width), Ok(output));
|
||||
assert_eq!(render(&source, width - 1), Err(RenderError::TooWide));
|
||||
assert_eq!(
|
||||
render("graph TD; A", /*max_width*/ 0),
|
||||
Err(RenderError::TooWide)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstruct_every_edge_from_rendered_paths() {
|
||||
// All 512 directed graphs on three nodes, including self-loops, cycles, fan-in and fan-out.
|
||||
// Reconstruct connections from the emitted glyphs without consulting the renderer's layout.
|
||||
for (mask, direction) in
|
||||
(0u16..512).flat_map(|mask| ["TD", "BT", "LR", "RL"].map(|direction| (mask, direction)))
|
||||
{
|
||||
let mut source = format!("graph {direction}; A; B; C;");
|
||||
let mut expected = Vec::new();
|
||||
for from in 0..3 {
|
||||
for to in 0..3 {
|
||||
if mask & (1 << (from * 3 + to)) != 0 {
|
||||
let a = char::from(b'A' + from);
|
||||
let b = char::from(b'A' + to);
|
||||
source.push_str(&format!("{a}-->{b};"));
|
||||
expected.push((a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let output = render(&source, /*max_width*/ 100).unwrap();
|
||||
let mut rows = output
|
||||
.lines()
|
||||
.map(|line| line.chars().collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>();
|
||||
if matches!(direction, "LR" | "RL") {
|
||||
let width = rows.iter().map(Vec::len).max().unwrap();
|
||||
rows = (0..width)
|
||||
.map(|x| {
|
||||
rows.iter()
|
||||
.map(|row| match row.get(x).copied().unwrap_or(' ') {
|
||||
'─' => '│',
|
||||
'│' => '─',
|
||||
'┐' => '└',
|
||||
'└' => '┐',
|
||||
'┬' => '├',
|
||||
'▲' => '◄',
|
||||
other => other,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let mut order = Vec::new();
|
||||
let mut owners = vec![' '; rows.len()];
|
||||
for (top, row) in rows.iter().enumerate() {
|
||||
if row.first() != Some(&'┌') {
|
||||
continue;
|
||||
}
|
||||
let bottom = (top + 1..rows.len())
|
||||
.find(|y| rows[*y].first() == Some(&'└'))
|
||||
.unwrap();
|
||||
let owner = rows[top..=bottom]
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|ch| matches!(ch, 'A' | 'B' | 'C'))
|
||||
.unwrap();
|
||||
owners[top..=bottom].fill(*owner);
|
||||
order.push(*owner);
|
||||
}
|
||||
assert_eq!(
|
||||
order,
|
||||
if matches!(direction, "BT" | "RL") {
|
||||
vec!['C', 'B', 'A']
|
||||
} else {
|
||||
vec!['A', 'B', 'C']
|
||||
}
|
||||
);
|
||||
let mut actual = Vec::new();
|
||||
for (y, row) in rows.iter().enumerate() {
|
||||
if let Some(port) = row.windows(2).position(|pair| pair == ['├', '─']) {
|
||||
let lane = (port + 1..row.len())
|
||||
.find(|x| matches!(row[*x], '┐' | '┘'))
|
||||
.unwrap();
|
||||
let mut target = y;
|
||||
loop {
|
||||
target = if row[lane] == '┐' {
|
||||
target + 1
|
||||
} else {
|
||||
target - 1
|
||||
};
|
||||
let ch = rows[target][lane];
|
||||
if matches!(ch, '┘' | '┐') {
|
||||
break;
|
||||
}
|
||||
assert!(matches!(ch, '│' | '╪'), "broken vertical path: {source}");
|
||||
}
|
||||
assert_eq!(&rows[target][port..port + 2], &['├', '◄']);
|
||||
assert!(
|
||||
rows[target][port + 2..lane]
|
||||
.iter()
|
||||
.all(|ch| matches!(ch, '─' | '╪'))
|
||||
);
|
||||
actual.push((owners[y], owners[target]));
|
||||
}
|
||||
}
|
||||
actual.sort_unstable();
|
||||
assert_eq!(actual, expected, "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_spans_distinguish_labels_from_matching_endpoint_glyphs() {
|
||||
use super::Role;
|
||||
|
||||
let lines = super::render_spans("sequenceDiagram; A-xB: x", /*max_width*/ 100).unwrap();
|
||||
let roles = lines
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|span| span.text.chars().filter(|ch| *ch == 'x').map(|_| span.role))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(roles, vec![Role::Text, Role::Edge]);
|
||||
assert_eq!(
|
||||
lines[0]
|
||||
.iter()
|
||||
.find(|span| span.text.contains('┌'))
|
||||
.unwrap()
|
||||
.role,
|
||||
Role::Node
|
||||
);
|
||||
for direction in ["TD", "BT", "LR", "RL"] {
|
||||
let lines = super::render_spans(
|
||||
&format!("flowchart {direction}; A --> B"),
|
||||
/*max_width*/ 100,
|
||||
)
|
||||
.unwrap();
|
||||
let ports = lines
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|span| {
|
||||
span.text
|
||||
.chars()
|
||||
.filter(|ch| matches!(ch, '├' | '┬'))
|
||||
.map(|_| span.role)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ports, vec![Role::Node, Role::Node]);
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "families_tests.rs"]
|
||||
mod families_tests;
|
||||
Reference in New Issue
Block a user