diff --git a/codex-rs/mermaid/README.md b/codex-rs/mermaid/README.md index 46f9a04d8d..ab91ff1c9d 100644 --- a/codex-rs/mermaid/README.md +++ b/codex-rs/mermaid/README.md @@ -6,13 +6,13 @@ production dependency is needed. ## Supported subsets -| Family | Supported syntax | -| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `flowchart`, `graph` | TD/TB (default), BT, LR, RL; rectangle `[label]`, decision `{label}`, and stadium `([label])` nodes; solid `-->`/`---`/`<-->` and dashed `-.->`/`-.-`/`<-.->` edges; pipe labels and spaced directed infix labels (`-- text -->`, `-. text .->`); `&` fan-out/fan-in, chains, branches, merges, loops | -| `sequenceDiagram` | Implicit participants, `participant`/`actor`, aliases, `->`, `->>`, `-->`, `-->>`, `-x`, `--x`, self-messages, `Note over A[,B]`, nested `loop`/`alt`/`opt`/`critical`/`break`, one labeled `else` per `alt` | -| `stateDiagram-v2`, `stateDiagram` | Flat states, `state "label" as ID`, descriptions, directed transitions with optional labels, initial/final `[*]`, direction declarations | -| `classDiagram` | `class ID`, multiline member bodies, `ID : member`, solid/dashed links, association, inheritance, composition, aggregation, dependency, realization, quoted endpoint cardinalities, relationship labels, direction declarations | -| `erDiagram` | Entities, multiline attribute bodies, `type name [PK, FK, UK] ["comment"]`, all four endpoint cardinalities, identifying/non-identifying relationships, relationship labels, direction declarations | +| Family | Supported syntax | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `flowchart`, `graph` | TD/TB (default), BT, LR, RL; rectangle `[label]`, decision `{label}`, and stadium `([label])` nodes; solid `-->`/`---`/`<-->` and dashed `-.->`/`-.-`/`<-.->` edges; pipe labels and spaced directed infix labels (`-- text -->`, `-. text .->`); `&` fan-out/fan-in, chains, branches, merges, loops; flat named `subgraph title` or `subgraph ID[title]` blocks closed by `end`, including edges between nodes in different groups | +| `sequenceDiagram` | Implicit participants, `participant`/`actor`, aliases, `->`, `->>`, `-->`, `-->>`, `-x`, `--x`, self-messages, `Note over A[,B]`, nested `loop`/`alt`/`opt`/`critical`/`break`, one labeled `else` per `alt` | +| `stateDiagram-v2`, `stateDiagram` | Flat states, `state "label" as ID`, descriptions, directed transitions with optional labels, initial/final `[*]`, direction declarations | +| `classDiagram` | `class ID`, multiline member bodies, `ID : member`, solid/dashed links, association, inheritance, composition, aggregation, dependency, realization, quoted endpoint cardinalities, relationship labels, direction declarations | +| `erDiagram` | Entities, multiline attribute bodies, `type name [PK, FK, UK] ["comment"]`, all four endpoint cardinalities, identifying/non-identifying relationships, relationship labels, direction declarations | Identifiers are ASCII letters followed by letters, digits, or underscores. Text supports ordinary Unicode and CJK. Full-line `%%` comments and @@ -31,7 +31,8 @@ semicolons. Flowchart node labels support `
`, `
`, and `
` as line breaks. Other HTML and entity escapes remain unsupported. These are explicit subsets, not complete Mermaid compatibility. Compound states, -flowchart subgraphs, other shapes, sequence activation and parallel fragments, +nested flowchart subgraphs, edges to subgraph IDs, subgraph-local directions, +other shapes, sequence activation and parallel fragments, styling, front matter, directives, other HTML, escapes, combining/zero-width characters, and ligatures with non-additive widths return errors. Callers should retain source on any error; the library never returns a partial diagram. diff --git a/codex-rs/mermaid/src/draw.rs b/codex-rs/mermaid/src/draw.rs index 3d42d0a0fb..2a2a385590 100644 --- a/codex-rs/mermaid/src/draw.rs +++ b/codex-rs/mermaid/src/draw.rs @@ -1,6 +1,7 @@ //! Orthogonal routes with unique lanes and endpoint positions, in all four directions. //! //! Routes never share segments. Crossings are explicitly marked; labels occupy reserved gutters. +//! Flat flowchart groups reserve frames around their nodes and internal routes. use super::Direction; use super::Graph; @@ -74,23 +75,100 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, } }) .collect::>(); - 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 grouped = !graph.subgraphs.is_empty(); + let inset = if grouped { 2 } else { 0 }; + let mut membership = vec![None; graph.nodes.len()]; + for (group, subgraph) in graph.subgraphs.iter().enumerate() { + for &node in &subgraph.nodes { + membership[node] = Some(group); + } } - 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 - }; + // Keep a group's members contiguous even when an edge referenced them before its declaration. + let mut order = Vec::new(); + for (node, &group) in membership.iter().enumerate() { + if order.contains(&node) { + continue; + } + if let Some(group) = group { + let mut members = graph.subgraphs[group].nodes.clone(); + members.sort_unstable(); + order.extend(members); + } else { + order.push(node); + } + } + if matches!(graph.direction, Direction::Up | Direction::Left) { + order.reverse(); + } + let mut starts = vec![0; graph.nodes.len()]; + let mut frames = vec![(0, 0); graph.subgraphs.len()]; + let mut along = 0; + let mut position = 0; + while position < order.len() { + let node = order[position]; + if let Some(group) = membership[node] { + let frame_start = along; + along += 2; + while position < order.len() && membership[order[position]] == Some(group) { + let node = order[position]; + starts[node] = along; + along += sizes[node] + 2; + position += 1; + } + if horizontal { + along = along.max(frame_start + graph.subgraphs[group].label.width() + 4); + } + frames[group] = (frame_start, along - 1); + along += 2; + } else { + starts[node] = along; + along += sizes[node] + 2; + position += 1; + } + } + let first_lane = inset + box_cross + if horizontal { 4 } else { label_width + 5 }; + let internal = graph + .edges + .iter() + .map(|edge| membership[edge.from].is_some() && membership[edge.from] == membership[edge.to]) + .collect::>(); + let internal_count = internal.iter().filter(|&&value| value).count(); + let mut frame_cross = inset + box_cross + 2; + if !graph.edges.is_empty() { + frame_cross = frame_cross.max(first_lane + internal_count * 2 + 1); + } + if !horizontal { + frame_cross = frame_cross.max( + graph + .subgraphs + .iter() + .map(|group| group.label.width() + 4) + .max() + .unwrap_or(0), + ); + } + let external_lane = if grouped { frame_cross + 2 } else { first_lane }; + let mut next_internal = 0; + let mut next_external = 0; + let lanes = internal + .iter() + .map(|&internal| { + if internal { + let lane = first_lane + next_internal * 2; + next_internal += 1; + lane + } else { + let lane = external_lane + next_external * 2; + next_external += 1; + lane + } + }) + .collect::>(); + let across = lanes + .iter() + .max() + .map_or(inset + box_cross, |lane| lane + 1) + .max(if grouped { frame_cross } else { 0 }); let (width, height) = if horizontal { (along - 2, across) } else { @@ -106,6 +184,30 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, cells: vec![vec![Cell::edge(' '); width]; height], horizontal, }; + for (group, &(start, end)) in frames.iter().enumerate() { + for x in 1..frame_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(frame_cross - 1, y, Cell::node('│')); + } + for (x, y, ch) in [ + (0, start, '┌'), + (frame_cross - 1, start, '┐'), + (0, end, '└'), + (frame_cross - 1, end, '┘'), + ] { + canvas.set(x, y, Cell::node(ch)); + } + let (x, y) = if horizontal { + (start + 2, 0) + } else { + (2, start) + }; + put_text(&mut canvas.cells[y], x, &graph.subgraphs[group].label)?; + } for (i, lines) in labels.iter().enumerate() { let start = starts[i]; let end = start + sizes[i] - 1; @@ -113,23 +215,23 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, 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)); + canvas.set(inset, start, Cell::node(top_left)); + canvas.set(inset + box_cross - 1, start, Cell::node(top_right)); + canvas.set(inset, end, Cell::node(bottom_left)); + canvas.set(inset + 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('─')); + canvas.set(inset + x, start, Cell::node('─')); + canvas.set(inset + 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('│')); + canvas.set(inset, y, Cell::node('│')); + canvas.set(inset + box_cross - 1, y, Cell::node('│')); } for (j, line) in lines.iter().enumerate() { let (x, y) = if horizontal { - (start + 2, j + 1) + (start + 2, inset + j + 1) } else { - (2, start + j + 1) + (inset + 2, start + j + 1) }; put_text(&mut canvas.cells[y], x, line)?; } @@ -154,19 +256,20 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, 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 { '│' }), - ); + canvas.set(lanes[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; + let lane = lanes[i]; for y in [source, target] { - for x in box_cross..lane { - let ch = if matches!(canvas.get(x, y), '│' | '┆') { + for x in inset + box_cross..lane { + let ch = if grouped + && x == frame_cross - 1 + && membership[if y == source { edge.from } else { edge.to }].is_some() + { + '┼' + } else if matches!(canvas.get(x, y), '│' | '┆') { '╪' } else if edge.dashed { '┄' @@ -176,10 +279,10 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, 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(inset + box_cross - 1, source, Cell::node('├')); + canvas.set(inset + box_cross - 1, target, Cell::node('├')); + canvas.set(inset + box_cross, source, Cell::edge(edge.source_tip)); + canvas.set(inset + box_cross, target, Cell::edge(edge.target_tip)); canvas.set( lane, source, @@ -192,9 +295,9 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result>, ); for (port, label) in [(source, &edge.label), (target, &edge.target_label)] { let (x, y) = if horizontal { - (port + 1, box_cross + 1) + (port + 1, inset + box_cross + 1) } else { - (box_cross + 2, port) + (inset + box_cross + 2, port) }; put_text(&mut canvas.cells[y], x, label)?; } diff --git a/codex-rs/mermaid/src/lib.rs b/codex-rs/mermaid/src/lib.rs index 684b03e69b..a8d7a0cccd 100644 --- a/codex-rs/mermaid/src/lib.rs +++ b/codex-rs/mermaid/src/lib.rs @@ -141,11 +141,19 @@ impl Edge { } } +#[derive(Debug, PartialEq, Eq)] +struct Subgraph { + id: String, + label: String, + nodes: Vec, +} + #[derive(Debug, Default, PartialEq, Eq)] struct Graph { direction: Direction, nodes: Vec, edges: Vec, + subgraphs: Vec, } impl Graph { diff --git a/codex-rs/mermaid/src/parse.rs b/codex-rs/mermaid/src/parse.rs index c31b66f799..d31190929c 100644 --- a/codex-rs/mermaid/src/parse.rs +++ b/codex-rs/mermaid/src/parse.rs @@ -1,5 +1,5 @@ //! 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. +//! Node groups expand into explicit edges within the graph edge cap; flat subgraphs retain membership. use super::Direction; use super::Edge; @@ -8,6 +8,7 @@ use super::MAX_EDGES; use super::MAX_LABEL; use super::RenderError; use super::Shape; +use super::Subgraph; use super::syntax::delimited_label; use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthStr; @@ -23,9 +24,69 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result { direction, ..Graph::default() }; - for statement in body { - let mut rest = *statement; - let mut from = nodes(&mut rest, &mut graph)?; + let mut block = None; + for &statement in body { + if let Some(text) = statement + .strip_prefix("subgraph") + .and_then(|rest| rest.strip_prefix([' ', '\t'])) + { + if block.is_some() { + return Err(RenderError::Unsupported); + } + if graph.subgraphs.len() == super::MAX_NODES { + return Err(RenderError::Limit); + } + let text = text.trim(); + let (id, label) = if let Some((id, after)) = + text.split_once('[').filter(|_| !text.starts_with('"')) + { + let mut rest = id.trim(); + let id = identifier(&mut rest)?; + if !rest.is_empty() { + return Err(RenderError::Unsupported); + } + let (label, rest) = delimited_label(after, "]")?; + if !rest.trim().is_empty() { + return Err(RenderError::Unsupported); + } + (id.to_owned(), flowchart_label(label)?) + } else { + if !text.starts_with('"') + && ["--", "==", "-.", ".-", "~~~"] + .iter() + .any(|operator| text.contains(operator)) + { + return Err(RenderError::Unsupported); + } + let label = flowchart_label(text)?; + let id = if label.chars().any(char::is_whitespace) { + format!("subGraph{}", graph.subgraphs.len()) + } else { + label.to_owned() + }; + (id, label) + }; + check_label(label)?; + if id.is_empty() || graph.subgraphs.iter().any(|group| group.id == id) { + return Err(RenderError::Unsupported); + } + block = Some(graph.subgraphs.len()); + graph.subgraphs.push(Subgraph { + id, + label: label.to_owned(), + nodes: Vec::new(), + }); + continue; + } + if statement == "end" { + let index = block.take().ok_or(RenderError::Unsupported)?; + if graph.subgraphs[index].nodes.is_empty() { + return Err(RenderError::Unsupported); + } + continue; + } + let mut rest = statement; + let mut from = nodes(&mut rest, &mut graph, block)?; while !rest.trim_start().is_empty() { rest = rest.trim_start(); let mut label = String::new(); @@ -75,7 +136,7 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result { check_label(&label)?; ('─', '◄', dashed) }; - let to = nodes(&mut rest, &mut graph)?; + let to = nodes(&mut rest, &mut graph, block)?; // Check the Cartesian expansion before allocating edges, including repeated IDs. if from.len() * to.len() > MAX_EDGES - graph.edges.len() { return Err(RenderError::Limit); @@ -96,25 +157,34 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result { from = to; } } - if graph.nodes.is_empty() { + if block.is_some() + || graph.nodes.is_empty() + || graph.subgraphs.iter().any(|group| { + group.nodes.is_empty() || graph.nodes.iter().any(|node| node.id == group.id) + }) + { return Err(RenderError::Unsupported); } Ok(graph) } -fn nodes(rest: &mut &str, graph: &mut Graph) -> Result, RenderError> { - let mut nodes = vec![node(rest, graph)?]; +fn nodes( + rest: &mut &str, + graph: &mut Graph, + block: Option, +) -> Result, RenderError> { + let mut nodes = vec![node(rest, graph, block)?]; 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)?); + nodes.push(node(rest, graph, block)?); } Ok(nodes) } -fn node(rest: &mut &str, graph: &mut Graph) -> Result { +fn node(rest: &mut &str, graph: &mut Graph, block: Option) -> Result { let id = identifier(rest)?; // Reserved constructs must not be interpreted as ordinary node declarations. if matches!( @@ -137,6 +207,14 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result { _ => None, }; let index = graph.node(id)?; + if let Some(block) = block + && !graph + .subgraphs + .iter() + .any(|group| group.nodes.contains(&index)) + { + graph.subgraphs[block].nodes.push(index); + } if let Some((open, close, shape)) = declaration { let (label, remaining) = delimited_label(&rest[open.len()..], close)?; let label = flowchart_label(label)? diff --git a/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__flat_subgraphs_and_cross_group_edges.snap b/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__flat_subgraphs_and_cross_group_edges.snap new file mode 100644 index 0000000000..d7ff2a9b86 --- /dev/null +++ b/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__flat_subgraphs_and_cross_group_edges.snap @@ -0,0 +1,43 @@ +--- +source: mermaid/src/tests.rs +expression: output +--- + ┌────────┐ + │ Z │ + │ ├───────────────────┐ + └────────┘ │ + │ + │ +┌─Old approach──────────────┐ │ +│ │ │ +│ ┌────────┐ │ │ +│ │ Input │ │ │ +│ │ ├◄───────────────┼──┘ +│ │ ├────────────┐ │ +│ └────────┘ │ │ +│ │ │ +│ │ │ +│ ┌────────┐ │ │ +│ │ Output │ │ │ +│ │ ├◄───────────┘ │ +│ │ ├──compare───────┼────┐ +│ └────────┘ │ │ +│ │ │ +└───────────────────────────┘ │ + │ + │ +┌─New approach──────────────┐ │ +│ │ │ +│ ┌────────┐ │ │ +│ │ Input │ │ │ +│ │ ├──────────────┐ │ │ +│ │ ├◄─────────────╪─┼────┘ +│ └────────┘ │ │ +│ │ │ +│ │ │ +│ ┌────────┐ │ │ +│ │ Output │ │ │ +│ │ ├◄─────────────┘ │ +│ └────────┘ │ +│ │ +└───────────────────────────┘ diff --git a/codex-rs/mermaid/src/tests.rs b/codex-rs/mermaid/src/tests.rs index eaa2ffaacb..19bdad5c57 100644 --- a/codex-rs/mermaid/src/tests.rs +++ b/codex-rs/mermaid/src/tests.rs @@ -206,6 +206,101 @@ fn branches_merges_and_retry_loop() { 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![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 [ @@ -220,7 +315,6 @@ fn rejects_partial_or_unsupported_input() { 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", diff --git a/codex-rs/tui/src/markdown_render/mermaid_tests.rs b/codex-rs/tui/src/markdown_render/mermaid_tests.rs index 86bec99b67..bf458ff0a8 100644 --- a/codex-rs/tui/src/markdown_render/mermaid_tests.rs +++ b/codex-rs/tui/src/markdown_render/mermaid_tests.rs @@ -21,6 +21,7 @@ fn mermaid_fences_use_native_renderer_for_every_family() { for source in [ "%% heading\nflowchart TD; A --> B", "graph LR; A --> B", + "flowchart TB; subgraph Old[Old approach]; A --> B; end; subgraph New[New approach]; C --> D; end; B --> C", "flowchart; A -- send --> B & C; B <-.-> C", "sequenceDiagram; A->>B: request; B-->>A: response", "stateDiagram-v2; [*] --> Active; Active --> [*]",