Render multiline Mermaid flowchart edge labels (#62550)

## Why

The terminal renderer already supports line breaks in flowchart node
labels. The same syntax in an edge label causes the diagram to fall
back to source text.

## What changed

Treat `<br>`, `<br/>`, and `<br />` as line breaks in edge labels.
For example, `A -->|"Review<br/>order"| B` renders the label on two
lines. Reserve space for each line and preserve blank lines without
erasing edge connectors.

## Testing

Add snapshots for all four layout directions and update the terminal
Markdown snapshot to include a multiline edge label. Test blank lines
and terminal width limits.

GitOrigin-RevId: 277525d92c6c1f105bc34516893c67eccc22a22c
This commit is contained in:
Eric Traut
2026-11-19 16:44:44 +00:00
committed by copyberry
parent ab00c6d640
commit 76aa618787
7 changed files with 206 additions and 41 deletions
+1 -1
View File
@@ -27,7 +27,7 @@ return types. ER attribute types and names use the identifier grammar above.
Flowchart node and edge labels may be enclosed in double quotes. Literal
ampersands are supported in labels, as is printable punctuation after parsing.
Quotes protect flowchart label delimiters such as brackets, pipes, and
semicolons. Flowchart node labels support `<br>`, `<br/>`, and `<br />` as
semicolons. Flowchart node and edge labels support `<br>`, `<br/>`, and `<br />` as
line breaks. Other HTML and entity escapes remain unsupported.
These are explicit subsets, not complete Mermaid compatibility. Compound states,
+30 -5
View File
@@ -39,9 +39,17 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>,
.edges
.iter()
.flat_map(|edge| [&edge.label, &edge.target_label])
.map(|label| label.width())
.flat_map(|label| label.split('\n'))
.map(UnicodeWidthStr::width)
.max()
.unwrap_or(0);
let label_height = graph
.edges
.iter()
.flat_map(|edge| [&edge.label, &edge.target_label])
.map(|label| label.split('\n').count())
.max()
.unwrap_or(1);
let box_cross = if horizontal {
labels.iter().map(Vec::len).max().unwrap_or(0) + 2
} else {
@@ -53,13 +61,22 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>,
.unwrap_or(0)
+ 4
};
// Vertical ports reserve one row per label line; horizontal ports use the width stride.
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;
counts[edge.from] += if horizontal {
1
} else {
edge.label.split('\n').count()
};
let target = counts[edge.to];
counts[edge.to] += 1;
counts[edge.to] += if horizontal {
1
} else {
edge.target_label.split('\n').count()
};
ports.push((source, target));
}
let stride = if horizontal { label_width + 2 } else { 1 };
@@ -126,7 +143,13 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>,
position += 1;
}
}
let first_lane = inset + box_cross + if horizontal { 4 } else { label_width + 5 };
let first_lane = inset
+ box_cross
+ if horizontal {
label_height + 3
} else {
label_width + 5
};
let internal = graph
.edges
.iter()
@@ -299,7 +322,9 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>,
} else {
(inset + box_cross + 2, port)
};
put_text(&mut canvas.cells[y], x, label)?;
for (line_index, line) in label.split('\n').enumerate() {
put_text(&mut canvas.cells[y + line_index], x, line)?;
}
}
}
Ok(finish(canvas.cells))
+29 -15
View File
@@ -110,8 +110,7 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
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)?;
label = multiline_label(text)?;
rest = remaining;
}
(source, target, dashed)
@@ -132,8 +131,7 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
rest = remaining
.strip_prefix('>')
.ok_or(RenderError::Unsupported)?;
label = flowchart_label(text.trim())?.to_owned();
check_label(&label)?;
label = multiline_label(text.trim())?;
('─', '◄', dashed)
};
let to = nodes(&mut rest, &mut graph, block)?;
@@ -217,16 +215,7 @@ fn node(rest: &mut &str, graph: &mut Graph, block: Option<usize>) -> Result<usiz
}
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)?;
}
let label = multiline_label(label)?;
*rest = remaining;
let node = &mut graph.nodes[index];
if node.declared && (node.label != label || node.shape != shape) {
@@ -239,6 +228,25 @@ fn node(rest: &mut &str, graph: &mut Graph, block: Option<usize>) -> Result<usiz
Ok(index)
}
fn multiline_label(label: &str) -> Result<String, RenderError> {
let label = flowchart_label(label)?
.replace("<br>", "\n")
.replace("<br/>", "\n")
.replace("<br />", "\n");
if label.trim().is_empty() {
return Err(RenderError::Unsupported);
}
// Blank lines reserve space but must not paint spaces over an edge connector.
let lines = label
.split('\n')
.map(|line| {
check_label_content(line)?;
Ok(if line.trim().is_empty() { "" } else { line })
})
.collect::<Result<Vec<_>, RenderError>>()?;
Ok(lines.join("\n"))
}
fn flowchart_label(label: &str) -> Result<&str, RenderError> {
// Mermaid Markdown strings require rendering beyond ordinary quoted labels.
if label.starts_with("\"`") {
@@ -259,13 +267,19 @@ fn flowchart_label(label: &str) -> Result<&str, RenderError> {
}
pub(super) fn check_label(label: &str) -> Result<(), RenderError> {
if label.trim().is_empty() {
return Err(RenderError::Unsupported);
}
check_label_content(label)
}
fn check_label_content(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, '┌' | '┐' | '└' | '┘' | '├' | '┤' | '╪' | '◄')
@@ -0,0 +1,82 @@
---
source: mermaid/src/tests.rs
assertion_line: 52
expression: "cases.join(\"\\n\\n\")"
---
TD
┌────────┐
│ Source │
│ ├──one─────┐
│ │ two │
│ ├─┄retry┄┄┄╪┄┐
│ │ later │ ┆
│ ├◄─────────╪─╪─┐
└────────┘ │ ┆ │
│ ┆ │
│ ┆ │
┌────────┐ │ ┆ │
│ Target │ │ ┆ │
│ ├◄─────────┘ ┆ │
└────────┘ ┆ │
┆ │
┆ │
┌────────┐ ┆ │
│ Other │ ┆ │
│ ├◄┄┄┄┄┄┄┄┄┄┄┄┘ │
│ ├──x───────────┘
│ │ y
└────────┘
BT
┌────────┐
│ Other │
│ ├◄┄┄┄┄┄┄┄┄┄┄┄┐
│ ├──x─────────╪─┐
│ │ y ┆ │
└────────┘ ┆ │
┆ │
┆ │
┌────────┐ ┆ │
│ Target │ ┆ │
│ ├◄─────────┐ ┆ │
└────────┘ │ ┆ │
│ ┆ │
│ ┆ │
┌────────┐ │ ┆ │
│ Source │ │ ┆ │
│ ├──one─────┘ ┆ │
│ │ two ┆ │
│ ├─┄retry┄┄┄┄┄┘ │
│ │ later │
│ ├◄─────────────┘
└────────┘
LR
┌─────────────────────┐ ┌────────┐ ┌──────────────┐
│ Source │ │ Target │ │ Other │
└┬──────┬──────┬──────┘ └┬───────┘ └┬──────┬──────┘
│ │ ▲ ▲ ▲ │
│one ┆retry │ │ ┆ │x
│two ┆later │ │ ┆ │y
│ ┆ │ │ ┆ │
│ ┆ │ │ ┆ │
└──────╪──────╪──────────┘ ┆ │
┆ │ ┆ │
└┄┄┄┄┄┄╪┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘ │
│ │
└─────────────────────────────┘
RL
┌──────────────┐ ┌────────┐ ┌─────────────────────┐
│ Other │ │ Target │ │ Source │
└┬──────┬──────┘ └┬───────┘ └┬──────┬──────┬──────┘
▲ │ ▲ │ │ ▲
┆ │x │ │one ┆retry │
┆ │y │ │two ┆later │
┆ │ │ │ ┆ │
┆ │ │ │ ┆ │
┆ │ └───────────┘ ┆ │
┆ │ ┆ │
└┄┄┄┄┄┄╪┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘ │
│ │
└────────────────────────────────────┘
+53 -11
View File
@@ -36,6 +36,39 @@ fn stadiums_with_other_shapes_in_every_direction() {
assert_snapshot!(cases.join("\n\n"));
}
#[test]
fn multiline_edge_labels_in_every_direction() {
let mut cases = Vec::new();
for direction in ["TD", "BT", "LR", "RL"] {
let source = format!(
"flowchart {direction}; A[Source] -->|\"one<br/>two\"| B[Target]; A -. retry<br />later .-> C[Other]; C -->|x<br>y| A"
);
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}"));
}
for (with_spaces, empty) in [
("one<br> <br>two", "one<br><br>two"),
(" <br>go", "<br>go"),
] {
assert_eq!(
render(
&format!("flowchart TD; A -->|{with_spaces}| B"),
/*max_width*/ 100
)
.unwrap(),
render(
&format!("flowchart TD; A -->|{empty}| B"),
/*max_width*/ 100
)
.unwrap(),
);
}
assert_snapshot!(cases.join("\n\n"));
}
#[test]
fn equivalent_flowchart_forms_preserve_graph() {
let quoted = r#"A["Review & confirm;"] -->|"Yes & continue"| B{"Ready?"}
@@ -184,6 +217,7 @@ fn quoted_flowchart_labels_reject_malformed_and_unsafe_text() {
"\"before <b\"",
"\"one<br/><b>two</b>\"",
"\"one<br class='x'>two\"",
"\"one<br/>\t<br/>two\"",
"\"\u{1b}\"",
] {
for source in [
@@ -356,8 +390,6 @@ fn rejects_partial_or_unsupported_input() {
"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!(
@@ -381,6 +413,8 @@ fn source_graph_and_width_limits() {
format!("graph TD; A[\"{}\"]", "[]".repeat(21)),
format!("graph TD; A([{}])", "x".repeat(41)),
format!("graph TD; A[\"ok<br />{}\"]", "界".repeat(21)),
format!("graph TD; A -->|\"ok<br />{}\"| B", "界".repeat(21)),
format!("graph TD; A -->|\"one<br>{}<br>two\"| B", " ".repeat(41)),
format!(
"graph TD; {}",
(0..17).map(|n| format!("N{n};")).collect::<String>()
@@ -389,15 +423,23 @@ fn source_graph_and_width_limits() {
] {
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));
for source in [
format!(
"graph LR; A[\"{}<br/>{}\"] --> B[Done]",
"界".repeat(20),
"x".repeat(40)
),
format!(
"graph LR; A -->|\"{}<br/>{}\"| B",
"界".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)
@@ -47,7 +47,7 @@ fn mermaid_nested_fences_and_unicode() {
fn mermaid_quoted_labels_and_ampersands() {
let source = r#"```mermaid
flowchart LR
A["Your saved order"] --> B["Review & confirm"] --> C["DoorDash checkout"]
A["Your saved order"] -->|"Review<br/>order"| B["Review & confirm"] --> C["DoorDash checkout"]
```"#;
let output = markdown_text(source, /*width*/ 100);
assert!(output.starts_with('┌'));
@@ -1,14 +1,16 @@
---
source: tui/src/markdown_render/mermaid_tests.rs
assertion_line: 54
expression: output
---
┌──────────────────┐ ┌──────────────────┐ ┌───────────────────┐
│ Your saved order │ │ Review & confirm │ │ DoorDash checkout │
└┬─────────────────┘ └┬─┬───────────────┘ └┬──────────────────┘
│ ▲ │ ▲
│ │ │ │
│ │ │ │
│ │ │ │
└─────────────────────┘ │ │
│ │
└───────────────────┘
└┬─────────────────┘ └┬───────┬─────────┘ └┬──────────────────┘
│ ▲ │ ▲
│Review │ │ │
│order │ │ │
│ │ │ │
│ │ │ │
└─────────────────────┘ │ │
│ │
└─────────────┘