mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
## What changed Parse `subgraph title` and `subgraph ID[title]` blocks and render labeled frames around their nodes and internal edges. Support edges between nodes in different groups in all four flowchart directions. Keep nested subgraphs, edges to subgraph IDs, and subgraph-local directions unsupported, preserving source fallback for unsupported input. Document the expanded syntax subset. ## Testing Add snapshot and regression coverage for group rendering, cross-group edges, all four directions, width limits, and invalid or unsupported subgraphs. Extend TUI native-renderer coverage to include grouped flowcharts. GitOrigin-RevId: 5bed535bcd4991b53143e3a591eef04f46ef4bd1
548 lines
18 KiB
Rust
548 lines
18 KiB
Rust
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 flat_subgraphs_and_cross_group_edges() {
|
|
let body = r#"
|
|
Z --> A
|
|
subgraph Old["Old approach"]
|
|
A[Input] --> B[Output]
|
|
end
|
|
subgraph New["New approach"]
|
|
C[Input] --> D[Output]
|
|
end
|
|
B -->|compare| C
|
|
"#;
|
|
for direction in ["TB", "BT", "LR", "RL"] {
|
|
let source = format!("flowchart {direction}\n{body}");
|
|
let output = render(&source, /*max_width*/ 200).unwrap();
|
|
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
|
|
assert_eq!(render(&source, width - 1), Err(RenderError::TooWide));
|
|
if direction == "TB" {
|
|
assert_snapshot!(output);
|
|
}
|
|
}
|
|
assert_eq!(
|
|
render(
|
|
"graph; subgraph\tSimple title; A; end",
|
|
/*max_width*/ 100
|
|
),
|
|
render(
|
|
r#"graph; subgraph "Simple title"; A; end"#,
|
|
/*max_width*/ 100
|
|
),
|
|
);
|
|
assert!(
|
|
render(
|
|
r#"graph; subgraph "Old [deprecated]"; A; end"#,
|
|
/*max_width*/ 100
|
|
)
|
|
.unwrap()
|
|
.contains("Old [deprecated]")
|
|
);
|
|
assert!(
|
|
render(
|
|
r#"graph; subgraph "G --> H"; A; end"#,
|
|
/*max_width*/ 100
|
|
)
|
|
.unwrap()
|
|
.contains("G --> H")
|
|
);
|
|
let graph = super::parse::parse(
|
|
"graph",
|
|
&[
|
|
"subgraph Old",
|
|
"A --> C",
|
|
"end",
|
|
"subgraph New",
|
|
"C[Input] --> D",
|
|
"end",
|
|
],
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
graph
|
|
.subgraphs
|
|
.iter()
|
|
.map(|group| group.nodes.clone())
|
|
.collect::<Vec<_>>(),
|
|
vec![vec![0, 1], vec![2]]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_or_unsupported_subgraphs_keep_source() {
|
|
for source in [
|
|
"graph; end",
|
|
"graph; subgraph X; A",
|
|
"graph; subgraph X; end",
|
|
"graph; subgraph X; subgraph Y; A; end; end",
|
|
"graph; subgraph X; A; end; subgraph X; B; end",
|
|
"graph; subgraph X; A[First]; end; subgraph Y; A[Second]; end",
|
|
"graph; subgraph X; A; end; X --> A",
|
|
"graph; subgraph X; direction LR; A; end",
|
|
"graph; subgraph G --> H; A; end",
|
|
"graph; subgraph G -.-> H; A; end",
|
|
"graph; subgraph G ==> H; A; end",
|
|
"graph; subgraph G ~~~ H; A; end",
|
|
r#"graph; subgraph "`**Old**`"; A; end"#,
|
|
"graph; subgraph Old approach; A; end; subGraph0 --> B",
|
|
] {
|
|
assert_eq!(
|
|
render(source, /*max_width*/ 100),
|
|
Err(RenderError::Unsupported),
|
|
"{source}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[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; 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;
|