use super::*;
fn strip_mermaid_comment(line: &str) -> &str {
let bytes: &[u8] = line.as_bytes();
let mut in_quotes: bool = false;
let mut idx: usize = 0;
while idx < bytes.len() {
let blue_val: u8 = bytes[idx];
if blue_val == MERMAID_BYTE_DQUOTE {
in_quotes = !in_quotes;
} else if !in_quotes
&& blue_val == MERMAID_BYTE_PERCENT
&& idx + 1 < bytes.len()
&& bytes[idx + 1] == MERMAID_BYTE_PERCENT
{
return &line[..idx];
}
idx += 1;
}
line
}
#[must_use]
pub fn parse_mermaid_diagram(source: &str) -> MermaidDiagram {
let raw_lines: Vec<&str> = source
.lines()
.map(strip_mermaid_comment)
.filter(|line_item: &&str| !line_item.trim().is_empty())
.collect();
let lines: Vec<&str> = raw_lines
.iter()
.map(|left_val: &&str| left_val.trim())
.collect();
let header_low: String = lines
.first()
.map(|length_val: &&str| length_val.to_ascii_lowercase())
.unwrap_or_default();
if header_low.starts_with(MERMAID_KW_SEQUENCE) {
MermaidDiagram::Sequence(parse_mermaid_sequence(&lines))
} else if header_low.starts_with(MERMAID_KW_STATE) {
MermaidDiagram::State(parse_mermaid_state(&lines))
} else if header_low.starts_with(MERMAID_KW_CLASS) {
MermaidDiagram::Class(parse_mermaid_class(&lines))
} else if header_low.starts_with(MERMAID_KW_ER) {
MermaidDiagram::Er(parse_mermaid_er(&lines))
} else if header_low.starts_with(MERMAID_KW_PIE) {
MermaidDiagram::Pie(parse_mermaid_pie(&lines))
} else if header_low.starts_with(MERMAID_KW_GANTT) {
MermaidDiagram::Gantt(parse_mermaid_gantt(&lines))
} else if header_low.starts_with(MERMAID_KW_TIMELINE) {
MermaidDiagram::Timeline(parse_mermaid_timeline(&lines))
} else if header_low.starts_with(MERMAID_KW_MINDMAP) {
MermaidDiagram::Mindmap(parse_mermaid_mindmap(&raw_lines))
} else if header_low.starts_with(MERMAID_KW_XYCHART) {
MermaidDiagram::XyChart(parse_mermaid_xychart(&lines))
} else if header_low.starts_with(MERMAID_KW_GITGRAPH) {
MermaidDiagram::GitGraph(parse_mermaid_gitgraph(&lines))
} else {
MermaidDiagram::Flowchart(parse_mermaid_flowchart(&lines))
}
}
#[must_use]
pub fn measure_mermaid_diagram(diagram: &MermaidDiagram) -> Size {
match diagram {
MermaidDiagram::Flowchart(fc) | MermaidDiagram::State(fc) => measure_flowchart(fc),
MermaidDiagram::Sequence(seq) => {
let p_cnt: usize = seq.get_participants().len().max(2);
let m_cnt: usize = seq.get_messages().len().max(1);
let extra_h: f32 = if seq.get_blocks().is_empty() {
0.0
} else {
28.0
};
let width_val: f32 = ((p_cnt as f32) * 172.0 + 76.0).max(400.0);
let height_val: f32 = ((m_cnt as f32) * 48.0 + 168.0 + extra_h).max(210.0);
Size::new(width_val, height_val)
}
MermaidDiagram::Class(cls) => {
let cols: usize = cls.get_classes().len().clamp(1, 3);
let rows: usize = cls.get_classes().len().div_ceil(cols).max(1);
let max_members: usize = cls
.get_classes()
.iter()
.map(|char_item: &MermaidClassBox| {
char_item.get_members().len()
+ usize::from(!char_item.get_stereotype().is_empty())
})
.max()
.unwrap_or(2);
let box_h: f32 = 46.0 + (max_members as f32) * 18.0;
let span_width: f32 = ((cols as f32) * 246.0 + 60.0).max(400.0);
let span_height: f32 = ((rows as f32) * (box_h + 58.0) + 56.0).max(210.0);
Size::new(span_width, span_height)
}
MermaidDiagram::Er(er) => {
let cols: usize = er.get_entities().len().clamp(1, 3);
let rows: usize = er.get_entities().len().div_ceil(cols).max(1);
let max_attr: usize = er
.get_entities()
.iter()
.map(|event_ref: &MermaidErEntity| event_ref.get_attributes().len())
.max()
.unwrap_or(2);
let box_h: f32 = 44.0 + (max_attr as f32) * 18.0;
let weight_val: f32 = ((cols as f32) * 260.0 + 64.0).max(400.0);
let half_extent: f32 = ((rows as f32) * (box_h + 58.0) + 56.0).max(210.0);
Size::new(weight_val, half_extent)
}
MermaidDiagram::Pie(pie) => {
let legend_h: f32 = (pie.get_slices().len().max(1) as f32) * 26.0 + 72.0;
let height_val_primary: f32 = legend_h.max(250.0);
Size::new(560.0, height_val_primary)
}
MermaidDiagram::Gantt(gantt) => {
let row_cnt: usize = gantt.get_tasks().len().max(1);
let mut sec_cnt: usize = 0;
let mut last_sec: &str = "";
for task in gantt.get_tasks().iter() {
if task.get_section().as_str() != last_sec {
sec_cnt += 1;
last_sec = task.get_section().as_str();
}
}
let height_val_secondary: f32 =
((row_cnt as f32) * 32.0 + (sec_cnt as f32) * 26.0 + 96.0).max(180.0);
Size::new(680.0, height_val_secondary)
}
MermaidDiagram::Timeline(tl) => {
let cols: usize = tl.get_events().len().max(1);
let max_items: usize = tl
.get_events()
.iter()
.map(|error_val: &MermaidTimelineEvent| error_val.get_items().len())
.max()
.unwrap_or(1);
let width_val_primary: f32 = ((cols as f32) * 186.0 + 56.0).max(420.0);
let height_val_next: f32 = (128.0 + (max_items as f32) * 34.0).max(210.0);
Size::new(width_val_primary, height_val_next)
}
MermaidDiagram::Mindmap(mm) => {
let max_depth: usize = mm
.get_nodes()
.iter()
.map(|item_count: &MermaidMindmapNode| item_count.get_depth())
.max()
.unwrap_or(1);
let leaves: usize = mm.get_nodes().len().max(1);
let width_val_secondary: f32 = (((max_depth + 1) as f32) * 188.0 + 64.0).max(420.0);
let height_val_alt: f32 = ((leaves as f32) * 40.0 + 64.0).max(200.0);
Size::new(width_val_secondary, height_val_alt)
}
MermaidDiagram::XyChart(xy) => {
let cols: usize = xy.get_x_labels().len().max(4);
let width_val_next: f32 = ((cols as f32) * 76.0 + 136.0).max(480.0);
Size::new(width_val_next, 300.0)
}
MermaidDiagram::GitGraph(git) => {
let c_cnt: usize = git.get_commits().len().max(1);
let b_cnt: usize = git.get_branches().len().max(1);
let width_val_alt: f32 = ((c_cnt as f32) * 78.0 + 148.0).max(420.0);
let height_val_inner: f32 = ((b_cnt as f32) * 50.0 + 76.0).max(170.0);
Size::new(width_val_alt, height_val_inner)
}
}
}
pub fn draw_mermaid_diagram(
diagram: &MermaidDiagram,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
) {
let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
display_list.push(DrawCommand::FillRoundedRect {
rect: bounds,
color: eva.get_background(),
radius: CornerRadius::all(0.0),
border: Border::default(),
});
match diagram {
MermaidDiagram::Flowchart(fc) | MermaidDiagram::State(fc) => {
draw_flowchart(fc, bounds, display_list, tokens, eva);
}
MermaidDiagram::Sequence(seq) => draw_sequence(seq, bounds, display_list, tokens, eva),
MermaidDiagram::Class(cls) => draw_class_diagram(cls, bounds, display_list, tokens, eva),
MermaidDiagram::Er(er) => draw_er_diagram(er, bounds, display_list, tokens, eva),
MermaidDiagram::Pie(pie) => draw_pie_chart(pie, bounds, display_list, tokens, eva),
MermaidDiagram::Gantt(gantt) => draw_gantt_chart(gantt, bounds, display_list, tokens, eva),
MermaidDiagram::Timeline(tl) => draw_timeline(tl, bounds, display_list, tokens, eva),
MermaidDiagram::Mindmap(mm) => draw_mindmap(mm, bounds, display_list, tokens, eva),
MermaidDiagram::XyChart(xy) => draw_xychart(xy, bounds, display_list, tokens, eva),
MermaidDiagram::GitGraph(git) => draw_gitgraph(git, bounds, display_list, tokens, eva),
}
}
#[must_use]
pub(crate) fn mermaid_badge_label(diagram: &MermaidDiagram) -> &'static str {
match diagram {
MermaidDiagram::Flowchart(_) => MERMAID_BADGE_FLOWCHART,
MermaidDiagram::Sequence(_) => MERMAID_BADGE_SEQUENCE,
MermaidDiagram::State(_) => MERMAID_BADGE_STATE,
MermaidDiagram::Class(_) => MERMAID_BADGE_CLASS,
MermaidDiagram::Er(_) => MERMAID_BADGE_ER,
MermaidDiagram::Pie(_) => MERMAID_BADGE_PIE,
MermaidDiagram::Gantt(_) => MERMAID_BADGE_GANTT,
MermaidDiagram::Timeline(_) => MERMAID_BADGE_TIMELINE,
MermaidDiagram::Mindmap(_) => MERMAID_BADGE_MINDMAP,
MermaidDiagram::XyChart(_) => MERMAID_BADGE_XYCHART,
MermaidDiagram::GitGraph(_) => MERMAID_BADGE_GITGRAPH,
}
}
#[must_use]
pub(crate) fn mermaid_diagram_title(diagram: &MermaidDiagram) -> String {
match diagram {
MermaidDiagram::Pie(pie) => pie.get_title().clone(),
MermaidDiagram::Gantt(gantt) => gantt.get_title().clone(),
MermaidDiagram::Timeline(tl) => tl.get_title().clone(),
MermaidDiagram::XyChart(xy) => xy.get_title().clone(),
_ => String::new(),
}
}
#[must_use]
fn scale_rect_about(rect: Rect, origin: Point, zoom: f32) -> Rect {
Rect::new(
origin.get_x() + (rect.get_x() - origin.get_x()) * zoom,
origin.get_y() + (rect.get_y() - origin.get_y()) * zoom,
rect.get_width() * zoom,
rect.get_height() * zoom,
)
}
#[must_use]
fn scale_point_about(point_coords: Point, origin: Point, zoom: f32) -> Point {
Point::new(
origin.get_x() + (point_coords.get_x() - origin.get_x()) * zoom,
origin.get_y() + (point_coords.get_y() - origin.get_y()) * zoom,
)
}
#[must_use]
fn scale_corner_radius(radius: CornerRadius, zoom: f32) -> CornerRadius {
CornerRadius::new(
radius.get_top_left() * zoom,
radius.get_top_right() * zoom,
radius.get_bottom_right() * zoom,
radius.get_bottom_left() * zoom,
)
}
pub(crate) fn scale_mermaid_display_list(commands: &mut [DrawCommand], origin: Point, zoom: f32) {
if (zoom - 1.0).abs() <= 0.001 {
return;
}
for cmd in commands.iter_mut() {
match cmd {
DrawCommand::FillRoundedRect {
rect,
radius,
border,
..
} => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
if border.get_width() > 0.0 {
border.set_width((border.get_width() * zoom).max(0.75));
}
}
DrawCommand::LinearGradientRect { rect, radius, .. } => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
}
DrawCommand::BoxShadow { rect, radius, .. } => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
}
DrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
*blur_radius *= zoom;
}
DrawCommand::TextRun { rect, style, .. } => {
*rect = scale_rect_about(*rect, origin, zoom);
style.set_font_size((style.get_font_size() * zoom).clamp(7.0, 48.0));
}
DrawCommand::Line {
from, to, width, ..
} => {
*from = scale_point_about(*from, origin, zoom);
*to = scale_point_about(*to, origin, zoom);
*width = (*width * zoom).max(0.75);
}
DrawCommand::Circle { center, radius, .. } => {
*center = scale_point_about(*center, origin, zoom);
*radius *= zoom;
}
DrawCommand::Triangle { p0, p1, p2, .. } => {
*p0 = scale_point_about(*p0, origin, zoom);
*p1 = scale_point_about(*p1, origin, zoom);
*p2 = scale_point_about(*p2, origin, zoom);
}
DrawCommand::Image { rect, radius, .. }
| DrawCommand::SharedImage { rect, radius, .. } => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
}
DrawCommand::SpriteRegion { rect, .. } => {
*rect = scale_rect_about(*rect, origin, zoom);
}
DrawCommand::PushClip(rect) => {
*rect = scale_rect_about(*rect, origin, zoom);
}
DrawCommand::PushRoundedClip { rect, radius } => {
*rect = scale_rect_about(*rect, origin, zoom);
*radius = scale_corner_radius(*radius, zoom);
}
DrawCommand::Clear(_) | DrawCommand::TextCaret { .. } | DrawCommand::PopClip => {}
}
}
}
fn parse_mermaid_color(spec: &str) -> Option<Color> {
let trimmed: &str = spec.trim().trim_end_matches(';');
if let Some(hex) = trimmed.strip_prefix('#') {
if hex.len() == 3 {
let red_val: u8 = u8::from_str_radix(&hex[0..1], 16).ok()?;
let green_val: u8 = u8::from_str_radix(&hex[1..2], 16).ok()?;
let blue_val: u8 = u8::from_str_radix(&hex[2..3], 16).ok()?;
return Some(Color::rgba(
red_val * 17,
green_val * 17,
blue_val * 17,
255,
));
}
if hex.len() == 6 {
let rgb: u32 = u32::from_str_radix(hex, 16).ok()?;
return Some(Color::hex(rgb));
}
return None;
}
let low: String = trimmed.to_ascii_lowercase();
MERMAID_NAMED_COLORS
.binary_search_by_key(&low.as_str(), |&(entry_index, _): &(&str, u32)| entry_index)
.ok()
.map(|idx: usize| Color::hex(MERMAID_NAMED_COLORS[idx].1))
}
fn parse_mermaid_style_props(raw: &str) -> (Option<String>, Option<String>, Option<String>) {
let mut fill: Option<String> = None;
let mut stroke: Option<String> = None;
let mut text_color: Option<String> = None;
for part in raw.split(',') {
if let Some((entry_index, item_val)) = part.split_once(':') {
let key: String = entry_index.trim().to_ascii_lowercase();
let val: String = item_val.trim().trim_matches('"').to_string();
if val.is_empty() {
continue;
}
if key == MERMAID_CSS_FILL {
fill = Some(val);
} else if key == MERMAID_CSS_STROKE {
stroke = Some(val);
} else if key == MERMAID_CSS_COLOR {
text_color = Some(val);
}
}
}
(fill, stroke, text_color)
}
fn parse_flow_direction(tok: &str) -> MermaidFlowDirection {
match tok.trim().to_ascii_uppercase().as_str() {
"LR" => MermaidFlowDirection::LeftRight,
"RL" => MermaidFlowDirection::RightLeft,
"BT" => MermaidFlowDirection::BottomTop,
_ => MermaidFlowDirection::TopDown,
}
}
fn parse_mermaid_flowchart(lines: &[&str]) -> MermaidFlowchart {
let mut chart: MermaidFlowchart = MermaidFlowchart::default();
let mut start_idx: usize = 0;
if let Some(first) = lines.first() {
let low: String = first.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_FLOWCHART) || low.starts_with(MERMAID_KW_GRAPH) {
let dir_tok: &str = first.split_whitespace().nth(1).unwrap_or("TD");
chart.set_direction(parse_flow_direction(dir_tok));
start_idx = 1;
}
}
let mut sg_stack: Vec<usize> = Vec::new();
for raw_line in lines.iter().skip(start_idx) {
let line: &str = raw_line.trim().trim_end_matches(';');
if line.is_empty() {
continue;
}
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_SUBGRAPH) {
let rest: &str = line[MERMAID_KW_SUBGRAPH.len()..].trim();
let (sg_id, title): (String, String) = if let Some(lb) = rest.find('[')
&& let Some(rb) = rest.rfind(']')
&& rb > lb
{
let id_part: String = rest[..lb].trim().to_string();
let title_part: String = rest[lb + 1..rb].trim().trim_matches('"').to_string();
let resolved_id: String = if id_part.is_empty() {
title_part.clone()
} else {
id_part
};
(resolved_id, title_part)
} else {
let clean: String = rest.trim_matches('"').to_string();
(clean.clone(), clean)
};
let parent: Option<usize> = sg_stack.last().copied();
let idx: usize = chart.get_subgraphs().len();
let mut sg: MermaidSubgraph = MermaidSubgraph::new(title);
sg.set_id(sg_id).set_parent(parent);
chart.get_mut_subgraphs().push(sg);
sg_stack.push(idx);
continue;
}
if low == MERMAID_KW_END {
let _: Option<usize> = sg_stack.pop();
continue;
}
if low.starts_with(MERMAID_KW_DIRECTION) {
let dir_val: MermaidFlowDirection =
parse_flow_direction(&line[MERMAID_KW_DIRECTION.len()..]);
if let Some(&sg_idx) = sg_stack.last() {
chart.get_mut_subgraphs()[sg_idx].set_direction(Some(dir_val));
} else {
chart.set_direction(dir_val);
}
continue;
}
if low.starts_with(MERMAID_KW_CLASSDEF) {
let rest: &str = line[MERMAID_KW_CLASSDEF.len()..].trim();
if let Some((cls_name, props)) = rest.split_once(char::is_whitespace) {
let (fill, stroke, text_color): (Option<String>, Option<String>, Option<String>) =
parse_mermaid_style_props(props);
chart.get_mut_class_defs().push(MermaidClassDef::new(
cls_name.trim().to_string(),
fill,
stroke,
text_color,
));
}
continue;
}
if low.starts_with(MERMAID_KW_CLASS_DECL) {
let rest: &str = line[MERMAID_KW_CLASS_DECL.len()..].trim();
let mut parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 2 {
let cls_name: String = parts.pop().unwrap_or("").trim().to_string();
let nodes_joined: String = parts.join(" ");
for raw_id in nodes_joined.split(',') {
let nid: &str = raw_id.trim();
if !nid.is_empty() {
let resolved: String =
register_flow_node(&mut chart, nid, sg_stack.last().copied());
if let Some(node) = chart.get_mut_nodes().iter_mut().find(
|item_count: &&mut MermaidFlowNode| {
item_count.get_id().as_str() == resolved.as_str()
},
) && !node.get_classes().contains(&cls_name)
{
node.get_mut_classes().push(cls_name.clone());
}
}
}
}
continue;
}
if low.starts_with(MERMAID_KW_STYLE) {
let rest: &str = line[MERMAID_KW_STYLE.len()..].trim();
if let Some((nid, props)) = rest.split_once(char::is_whitespace) {
let (fill, stroke, text_color): (Option<String>, Option<String>, Option<String>) =
parse_mermaid_style_props(props);
let resolved: String =
register_flow_node(&mut chart, nid.trim(), sg_stack.last().copied());
if let Some(node) =
chart
.get_mut_nodes()
.iter_mut()
.find(|node_entry: &&mut MermaidFlowNode| {
node_entry.get_id().as_str() == resolved.as_str()
})
{
if fill.is_some() {
node.set_fill(fill);
}
if stroke.is_some() {
node.set_stroke(stroke);
}
if text_color.is_some() {
node.set_text_color(text_color);
}
}
}
continue;
}
if low.starts_with(MERMAID_KW_CLICK) {
let rest: &str = line[MERMAID_KW_CLICK.len()..].trim();
let mut toks: Vec<&str> = rest.split_whitespace().collect();
if toks.len() >= 2 {
let nid: &str = toks.remove(0);
let target: String = toks
.first()
.copied()
.unwrap_or("")
.trim_matches('"')
.to_string();
let resolved: String =
register_flow_node(&mut chart, nid, sg_stack.last().copied());
if let Some(node) =
chart
.get_mut_nodes()
.iter_mut()
.find(|normal_vec: &&mut MermaidFlowNode| {
normal_vec.get_id().as_str() == resolved.as_str()
})
{
node.set_click_url(Some(target));
}
}
continue;
}
if low.starts_with(MERMAID_KW_LINKSTYLE) {
continue;
}
let active_sg: Option<usize> = sg_stack.last().copied();
let chain: Vec<(String, Option<(MermaidEdgeStyle, String)>)> = parse_flow_edge_chain(line);
if chain.len() >= 2 {
for win_idx in 0..(chain.len() - 1) {
let lhs_group: &str = chain[win_idx].0.as_str();
let rhs_group: &str = chain[win_idx + 1].0.as_str();
let (style, label): (MermaidEdgeStyle, String) = chain[win_idx]
.1
.clone()
.unwrap_or((MermaidEdgeStyle::Solid, String::new()));
let lhs_nodes: Vec<String> = split_amp_nodes(lhs_group)
.into_iter()
.map(|tok: &str| register_flow_node(&mut chart, tok, active_sg))
.filter(|id: &String| !id.is_empty())
.collect();
let rhs_nodes: Vec<String> = split_amp_nodes(rhs_group)
.into_iter()
.map(|tok: &str| register_flow_node(&mut chart, tok, active_sg))
.filter(|id: &String| !id.is_empty())
.collect();
for from_id in lhs_nodes.iter() {
for to_id in rhs_nodes.iter() {
chart.get_mut_edges().push(MermaidFlowEdge::new(
from_id.clone(),
to_id.clone(),
label.clone(),
style,
));
}
}
}
} else {
for tok in split_amp_nodes(line) {
let _: String = register_flow_node(&mut chart, tok, active_sg);
}
}
}
apply_flowchart_class_defs(&mut chart);
chart
}
fn apply_flowchart_class_defs(chart: &mut MermaidFlowchart) {
let defs: Vec<MermaidClassDef> = chart.get_class_defs().clone();
if defs.is_empty() {
return;
}
for node in chart.get_mut_nodes().iter_mut() {
let cls_list: Vec<String> = node.get_classes().clone();
for cls_name in cls_list.iter() {
if let Some(def) = defs.iter().find(|delta_val: &&MermaidClassDef| {
delta_val.get_name().as_str() == cls_name.as_str()
}) {
if node.try_get_fill().is_none() && def.try_get_fill().is_some() {
node.set_fill(def.try_get_fill().clone());
}
if node.try_get_stroke().is_none() && def.try_get_stroke().is_some() {
node.set_stroke(def.try_get_stroke().clone());
}
if node.try_get_text_color().is_none() && def.try_get_text_color().is_some() {
node.set_text_color(def.try_get_text_color().clone());
}
}
}
}
}
fn split_amp_nodes(group: &str) -> Vec<&str> {
let bytes: &[u8] = group.as_bytes();
let mut parts: Vec<&str> = Vec::new();
let mut in_quotes: bool = false;
let mut depth_sq: usize = 0;
let mut depth_par: usize = 0;
let mut depth_cur: usize = 0;
let mut start: usize = 0;
for (idx, &blue_val) in bytes.iter().enumerate() {
if blue_val == MERMAID_BYTE_DQUOTE {
in_quotes = !in_quotes;
} else if !in_quotes {
match blue_val {
MERMAID_BYTE_LBRACKET => depth_sq += 1,
MERMAID_BYTE_RBRACKET => depth_sq = depth_sq.saturating_sub(1),
MERMAID_BYTE_LPAREN => depth_par += 1,
MERMAID_BYTE_RPAREN => depth_par = depth_par.saturating_sub(1),
MERMAID_BYTE_LBRACE => depth_cur += 1,
MERMAID_BYTE_RBRACE => depth_cur = depth_cur.saturating_sub(1),
MERMAID_BYTE_AMP if depth_sq == 0 && depth_par == 0 && depth_cur == 0 => {
let seg: &str = group[start..idx].trim();
if !seg.is_empty() {
parts.push(seg);
}
start = idx + 1;
}
_ => {}
}
}
}
let tail: &str = group[start..].trim();
if !tail.is_empty() {
parts.push(tail);
}
parts
}
fn match_flow_edge_op(slice: &str) -> Option<(usize, MermaidEdgeStyle, String)> {
let inline_patterns: [(&str, &str, MermaidEdgeStyle); 6] = [
("-. ", " .->", MermaidEdgeStyle::Dashed),
("-. ", " .-", MermaidEdgeStyle::DashedPlain),
("== ", " ==>", MermaidEdgeStyle::Thick),
("== ", " ===", MermaidEdgeStyle::ThickPlain),
("-- ", " -->", MermaidEdgeStyle::Solid),
("-- ", " ---", MermaidEdgeStyle::Plain),
];
for (open, close, style) in inline_patterns.into_iter() {
if let Some(after_open) = slice.strip_prefix(open)
&& let Some(close_pos) = after_open.find(close)
{
let text_value: String = after_open[..close_pos].trim().to_string();
let consumed: usize = open.len() + close_pos + close.len();
return Some((consumed, style, text_value));
}
}
let direct_ops: [(&str, MermaidEdgeStyle); 14] = [
("<-.->", MermaidEdgeStyle::DashedBidir),
("<-->", MermaidEdgeStyle::Bidir),
("<==>", MermaidEdgeStyle::ThickBidir),
("o--o", MermaidEdgeStyle::CircleBoth),
("x--x", MermaidEdgeStyle::CrossBoth),
("-.->", MermaidEdgeStyle::Dashed),
("-.-", MermaidEdgeStyle::DashedPlain),
("==>", MermaidEdgeStyle::Thick),
("===", MermaidEdgeStyle::ThickPlain),
("-->", MermaidEdgeStyle::Solid),
("---", MermaidEdgeStyle::Plain),
("--o", MermaidEdgeStyle::CircleEnd),
("--x", MermaidEdgeStyle::CrossEnd),
("->", MermaidEdgeStyle::Solid),
];
for (op, style) in direct_ops.into_iter() {
if let Some(after) = slice.strip_prefix(op) {
let trimmed_after: &str = after.trim_start();
let ws_len: usize = after.len() - trimmed_after.len();
if let Some(after_pipe) = trimmed_after.strip_prefix('|')
&& let Some(end_pipe) = after_pipe.find('|')
{
let label_str: String = after_pipe[..end_pipe].trim().to_string();
let consumed: usize = op.len() + ws_len + 1 + end_pipe + 1;
return Some((consumed, style, label_str));
}
return Some((op.len(), style, String::new()));
}
}
None
}
fn parse_flow_edge_chain(line: &str) -> Vec<(String, Option<(MermaidEdgeStyle, String)>)> {
let bytes: &[u8] = line.as_bytes();
let mut out: Vec<(String, Option<(MermaidEdgeStyle, String)>)> = Vec::new();
let mut in_quotes: bool = false;
let mut depth_sq: usize = 0;
let mut depth_par: usize = 0;
let mut depth_cur: usize = 0;
let mut seg_start: usize = 0;
let mut idx: usize = 0;
while idx < bytes.len() {
let blue_val: u8 = bytes[idx];
if blue_val == MERMAID_BYTE_DQUOTE {
in_quotes = !in_quotes;
idx += 1;
continue;
}
if !in_quotes {
if depth_sq == 0 && depth_par == 0 && depth_cur == 0 {
let prev_ok: bool = idx > seg_start;
if prev_ok
&& let Some((op_len, style, label_text)) = match_flow_edge_op(&line[idx..])
{
let lhs: String = line[seg_start..idx].trim().to_string();
if !lhs.is_empty() {
out.push((lhs, Some((style, label_text))));
idx += op_len;
seg_start = idx;
continue;
}
}
}
match blue_val {
MERMAID_BYTE_LBRACKET => depth_sq += 1,
MERMAID_BYTE_RBRACKET => depth_sq = depth_sq.saturating_sub(1),
MERMAID_BYTE_LPAREN => depth_par += 1,
MERMAID_BYTE_RPAREN => depth_par = depth_par.saturating_sub(1),
MERMAID_BYTE_LBRACE => depth_cur += 1,
MERMAID_BYTE_RBRACE => depth_cur = depth_cur.saturating_sub(1),
_ => {}
}
}
idx += 1;
}
let tail: String = line[seg_start..].trim().to_string();
if !tail.is_empty() {
out.push((tail, None));
}
out
}
fn register_flow_node(chart: &mut MermaidFlowchart, raw: &str, subgraph: Option<usize>) -> String {
let trimmed: &str = raw.trim();
if trimmed.is_empty() {
return String::new();
}
let (id, label, shape, explicit, classes): (
String,
String,
MermaidNodeShape,
bool,
Vec<String>,
) = parse_flow_node_token(trimmed);
if id.is_empty() {
return String::new();
}
if let Some(existing) = chart
.get_mut_nodes()
.iter_mut()
.find(|item_count: &&mut MermaidFlowNode| item_count.get_id().as_str() == id.as_str())
{
if explicit {
existing.set_label(label);
existing.set_shape(shape);
}
if existing.get_subgraph().is_none() && subgraph.is_some() {
existing.set_subgraph(subgraph);
}
for cls in classes.into_iter() {
if !existing.get_classes().contains(&cls) {
existing.get_mut_classes().push(cls);
}
}
return id;
}
let mut node: MermaidFlowNode = MermaidFlowNode::new(id.clone(), label, shape, subgraph);
node.set_classes(classes);
chart.get_mut_nodes().push(node);
id
}
fn parse_flow_node_token(token: &str) -> (String, String, MermaidNodeShape, bool, Vec<String>) {
let mut classes: Vec<String> = Vec::new();
let base_tok: &str = if let Some(sep_idx) = token.rfind(MERMAID_CLASS_SEP) {
let cls_part: &str = token[sep_idx + MERMAID_CLASS_SEP.len()..].trim();
for cls in cls_part.split(',') {
let text_value: &str = cls.trim();
if !text_value.is_empty() {
classes.push(text_value.to_string());
}
}
token[..sep_idx].trim()
} else {
token
};
let shapes: [(&str, &str, MermaidNodeShape); 14] = [
("(((", ")))", MermaidNodeShape::DoubleCircle),
("((", "))", MermaidNodeShape::Circle),
("([", "])", MermaidNodeShape::Stadium),
("[[", "]]", MermaidNodeShape::Subroutine),
("[(", ")]", MermaidNodeShape::Cylinder),
("{{", "}}", MermaidNodeShape::Hexagon),
("[/", "/]", MermaidNodeShape::Parallelogram),
("[\\", "\\]", MermaidNodeShape::ParallelogramAlt),
("[/", "\\]", MermaidNodeShape::Trapezoid),
("[\\", "/]", MermaidNodeShape::TrapezoidAlt),
(">", "]", MermaidNodeShape::Asymmetric),
("[", "]", MermaidNodeShape::Box),
("(", ")", MermaidNodeShape::Rounded),
("{", "}", MermaidNodeShape::Diamond),
];
for (open, close, shape) in shapes.into_iter() {
if let Some(open_idx) = base_tok.find(open)
&& let Some(close_idx) = base_tok.rfind(close)
&& close_idx >= open_idx + open.len()
&& base_tok[close_idx + close.len()..].trim().is_empty()
{
let id: String = base_tok[..open_idx].trim().to_string();
let raw_lbl: &str = base_tok[open_idx + open.len()..close_idx].trim();
let label_str: String = raw_lbl.trim_matches('"').to_string();
let resolved_id: String = if id.is_empty() { label_str.clone() } else { id };
return (resolved_id, label_str, shape, true, classes);
}
}
let clean: String = base_tok.trim_matches('"').to_string();
(clean.clone(), clean, MermaidNodeShape::Box, false, classes)
}
fn parse_mermaid_sequence(lines: &[&str]) -> MermaidSequence {
let mut seq: MermaidSequence = MermaidSequence::default();
let mut active_stacks: HashMap<usize, Vec<usize>> = HashMap::new();
let mut block_stack: Vec<MermaidSeqBlock> = Vec::new();
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low == MERMAID_KW_AUTONUMBER {
seq.set_autonumber(true);
continue;
}
if low.starts_with(MERMAID_KW_PARTICIPANT) || low.starts_with(MERMAID_KW_ACTOR) {
let is_actor: bool = low.starts_with(MERMAID_KW_ACTOR);
let prefix_len: usize = if is_actor {
MERMAID_KW_ACTOR.len()
} else {
MERMAID_KW_PARTICIPANT.len()
};
let rest: &str = line[prefix_len..].trim();
let (id, label): (String, String) =
if let Some((alpha_val, blue_val)) = rest.split_once(MERMAID_ALIAS_SEP) {
(alpha_val.trim().to_string(), blue_val.trim().to_string())
} else {
(rest.to_string(), rest.to_string())
};
let _: usize = ensure_seq_participant(&mut seq, &id, Some(&label), is_actor);
continue;
}
if low.starts_with(MERMAID_KW_ACTIVATE) {
let pid: &str = line[MERMAID_KW_ACTIVATE.len()..].trim();
let p_idx: usize = ensure_seq_participant(&mut seq, pid, None, false);
let row: usize = seq.get_messages().len();
active_stacks.entry(p_idx).or_default().push(row);
continue;
}
if low.starts_with(MERMAID_KW_DEACTIVATE) {
let pid: &str = line[MERMAID_KW_DEACTIVATE.len()..].trim();
let p_idx: usize = ensure_seq_participant(&mut seq, pid, None, false);
let end_row: usize = seq.get_messages().len().saturating_sub(1);
if let Some(start_row) = active_stacks.get_mut(&p_idx).and_then(Vec::pop) {
seq.get_mut_activations().push(MermaidSeqActivation::new(
p_idx,
start_row,
end_row.max(start_row),
));
}
continue;
}
if let Some((b_kind, b_lbl)) = parse_seq_block_open(line, &low) {
let start_row: usize = seq.get_messages().len();
let depth: usize = block_stack.len();
block_stack.push(MermaidSeqBlock::new(
b_kind,
b_lbl,
start_row,
start_row,
depth,
Vec::new(),
));
continue;
}
if low == MERMAID_KW_ELSE
|| low.starts_with("else ")
|| low == MERMAID_KW_AND
|| low.starts_with("and ")
|| low == MERMAID_KW_OPTION
|| low.starts_with("option ")
{
let div_lbl: String = line
.split_once(char::is_whitespace)
.map(|(_, text_value): (&str, &str)| text_value.trim().to_string())
.unwrap_or_default();
let row_idx: usize = seq.get_messages().len();
if let Some(top) = block_stack.last_mut() {
top.get_mut_dividers()
.push(MermaidSeqBlockDivider::new(row_idx, div_lbl));
}
continue;
}
if low == MERMAID_KW_END {
if let Some(mut blk) = block_stack.pop() {
let end_row: usize = seq
.get_messages()
.len()
.saturating_sub(1)
.max(blk.get_start_row());
blk.set_end_row(end_row);
seq.get_mut_blocks().push(blk);
}
continue;
}
if low.starts_with(MERMAID_KW_NOTE) {
if let Some((hdr, text)) = line.split_once(':') {
let hdr_after: &str = hdr[MERMAID_KW_NOTE.len()..].trim();
let hdr_low: String = hdr_after.to_ascii_lowercase();
let (placement, target_spec): (MermaidSeqNotePlacement, &str) =
if hdr_low.starts_with(MERMAID_NOTE_LEFT_OF) {
(
MermaidSeqNotePlacement::LeftOf,
hdr_after[MERMAID_NOTE_LEFT_OF.len()..].trim(),
)
} else if hdr_low.starts_with(MERMAID_NOTE_RIGHT_OF) {
(
MermaidSeqNotePlacement::RightOf,
hdr_after[MERMAID_NOTE_RIGHT_OF.len()..].trim(),
)
} else if hdr_low.starts_with(MERMAID_NOTE_OVER) {
(
MermaidSeqNotePlacement::Over,
hdr_after[MERMAID_NOTE_OVER.len()..].trim(),
)
} else {
(MermaidSeqNotePlacement::Over, hdr_after)
};
let (from_i, to_i): (usize, usize) =
if let Some((first_val, byte_val)) = target_spec.split_once(',') {
(
ensure_seq_participant(&mut seq, first_val.trim(), None, false),
ensure_seq_participant(&mut seq, byte_val.trim(), None, false),
)
} else if !target_spec.is_empty() {
let idx: usize = ensure_seq_participant(&mut seq, target_spec, None, false);
(idx, idx)
} else {
(0, 0)
};
let mut note_msg: MermaidSequenceMessage = MermaidSequenceMessage::new(
from_i,
to_i,
text.trim().to_string(),
MermaidEdgeStyle::Solid,
true,
);
note_msg.set_note_placement(placement);
seq.get_mut_messages().push(note_msg);
}
continue;
}
let seq_ops: [(&str, MermaidEdgeStyle); 8] = [
("-->>", MermaidEdgeStyle::Dashed),
("->>", MermaidEdgeStyle::Solid),
("--x", MermaidEdgeStyle::DashedCrossArrow),
("-x", MermaidEdgeStyle::CrossArrow),
("--)", MermaidEdgeStyle::DashedAsyncArrow),
("-)", MermaidEdgeStyle::AsyncArrow),
("-->", MermaidEdgeStyle::DashedOpenArrow),
("->", MermaidEdgeStyle::OpenArrow),
];
for (op, style) in seq_ops.into_iter() {
if let Some(pos) = line.find(op) {
let lhs: &str = line[..pos].trim();
let rhs_all: &str = line[pos + op.len()..].trim();
let (rhs_raw, msg): (&str, &str) = match rhs_all.split_once(':') {
Some((red_val, matrix_elems)) => (red_val.trim(), matrix_elems.trim()),
None => (rhs_all, ""),
};
let activate_target: bool = rhs_raw.starts_with('+');
let deactivate_source: bool = rhs_raw.starts_with('-');
let rhs: &str = rhs_raw.trim_start_matches(['+', '-']).trim();
if !lhs.is_empty() && !rhs.is_empty() {
let from_idx: usize = ensure_seq_participant(&mut seq, lhs, None, false);
let to_idx: usize = ensure_seq_participant(&mut seq, rhs, None, false);
let row_idx: usize = seq.get_messages().len();
seq.get_mut_messages().push(MermaidSequenceMessage::new(
from_idx,
to_idx,
msg.to_string(),
style,
false,
));
if activate_target {
active_stacks.entry(to_idx).or_default().push(row_idx);
}
if deactivate_source
&& let Some(start_row) = active_stacks.get_mut(&from_idx).and_then(Vec::pop)
{
seq.get_mut_activations().push(MermaidSeqActivation::new(
from_idx,
start_row,
row_idx.max(start_row),
));
}
}
break;
}
}
}
let last_row: usize = seq.get_messages().len().saturating_sub(1);
for (p_idx, stack) in active_stacks.into_iter() {
for start_row in stack.into_iter() {
seq.get_mut_activations().push(MermaidSeqActivation::new(
p_idx,
start_row,
last_row.max(start_row),
));
}
}
while let Some(mut blk) = block_stack.pop() {
blk.set_end_row(last_row.max(blk.get_start_row()));
seq.get_mut_blocks().push(blk);
}
seq
}
fn parse_seq_block_open(line: &str, low: &str) -> Option<(MermaidSeqBlockKind, String)> {
let table: [(&str, MermaidSeqBlockKind); 7] = [
(MERMAID_KW_LOOP, MermaidSeqBlockKind::Loop),
(MERMAID_KW_ALT, MermaidSeqBlockKind::Alt),
(MERMAID_KW_OPT, MermaidSeqBlockKind::Opt),
(MERMAID_KW_PAR, MermaidSeqBlockKind::Par),
(MERMAID_KW_CRITICAL, MermaidSeqBlockKind::Critical),
(MERMAID_KW_BREAK, MermaidSeqBlockKind::Break),
(MERMAID_KW_RECT, MermaidSeqBlockKind::Rect),
];
for (kw, kind) in table.into_iter() {
if low.starts_with(kw) {
return Some((kind, line[kw.len()..].trim().to_string()));
}
}
None
}
fn ensure_seq_participant(
seq: &mut MermaidSequence,
id: &str,
label: Option<&str>,
is_actor: bool,
) -> usize {
if let Some(pos) = seq
.get_participants()
.iter()
.position(|(pid, _): &(String, String)| pid.as_str() == id)
{
if let Some(label_text) = label {
seq.get_mut_participants()[pos].1 = label_text.to_string();
}
if is_actor && pos < seq.get_actor_flags().len() {
seq.get_mut_actor_flags()[pos] = true;
}
return pos;
}
let idx: usize = seq.get_participants().len();
let display: String = label.unwrap_or(id).to_string();
seq.get_mut_participants().push((id.to_string(), display));
seq.get_mut_actor_flags().push(is_actor);
idx
}
fn parse_mermaid_state(lines: &[&str]) -> MermaidFlowchart {
let mut chart: MermaidFlowchart = MermaidFlowchart::default();
let mut terminal_counter: usize = 0;
let mut note_counter: usize = 0;
let mut sg_stack: Vec<usize> = Vec::new();
let mut pending_note: Option<(String, Vec<String>)> = None;
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if let Some((ref target, ref mut body)) = pending_note {
if low == MERMAID_END_NOTE {
let target_id: String = target.clone();
let note_txt: String = body.join(" ");
pending_note = None;
attach_state_note(
&mut chart,
&target_id,
note_txt,
sg_stack.last().copied(),
&mut note_counter,
);
} else {
body.push(line.to_string());
}
continue;
}
if line == "}" {
let _: Option<usize> = sg_stack.pop();
continue;
}
if low.starts_with(MERMAID_KW_DIRECTION) {
let dir_val: MermaidFlowDirection =
parse_flow_direction(&line[MERMAID_KW_DIRECTION.len()..]);
if let Some(&sg_idx) = sg_stack.last() {
chart.get_mut_subgraphs()[sg_idx].set_direction(Some(dir_val));
} else {
chart.set_direction(dir_val);
}
continue;
}
if low.starts_with(MERMAID_KW_NOTE) {
let after: &str = line[MERMAID_KW_NOTE.len()..].trim();
let after_low: String = after.to_ascii_lowercase();
let target_raw: &str = if after_low.starts_with(MERMAID_NOTE_LEFT_OF) {
after[MERMAID_NOTE_LEFT_OF.len()..].trim()
} else if after_low.starts_with(MERMAID_NOTE_RIGHT_OF) {
after[MERMAID_NOTE_RIGHT_OF.len()..].trim()
} else {
after
};
if let Some((target_id, note_text)) = target_raw.split_once(':') {
attach_state_note(
&mut chart,
target_id.trim(),
note_text.trim().to_string(),
sg_stack.last().copied(),
&mut note_counter,
);
} else {
pending_note = Some((target_raw.trim().to_string(), Vec::new()));
}
continue;
}
if low.starts_with(MERMAID_KW_STATE_DECL) {
let rest: &str = line[MERMAID_KW_STATE_DECL.len()..].trim();
let rest_low: String = rest.to_ascii_lowercase();
if rest.ends_with('{') {
let header_part: &str = rest.trim_end_matches('{').trim();
let (sg_id, title): (String, String) =
if let Some((lhs, rhs)) = header_part.split_once(MERMAID_ALIAS_SEP) {
(
rhs.trim().to_string(),
lhs.trim().trim_matches('"').to_string(),
)
} else {
let clean: String = header_part.trim_matches('"').to_string();
(clean.clone(), clean)
};
let parent: Option<usize> = sg_stack.last().copied();
let idx: usize = chart.get_subgraphs().len();
let mut sg: MermaidSubgraph = MermaidSubgraph::new(title);
sg.set_id(sg_id).set_parent(parent);
chart.get_mut_subgraphs().push(sg);
sg_stack.push(idx);
continue;
}
if rest_low.contains(MERMAID_STATE_FORK)
|| rest_low.contains(MERMAID_STATE_JOIN)
|| rest_low.contains(MERMAID_STATE_FORK_ALT)
|| rest_low.contains(MERMAID_STATE_JOIN_ALT)
{
let id: String = rest
.split_whitespace()
.next()
.unwrap_or("")
.trim()
.to_string();
if !id.is_empty() {
upsert_state_node(
&mut chart,
id,
String::new(),
MermaidNodeShape::ForkJoin,
sg_stack.last().copied(),
);
}
continue;
}
if rest_low.contains(MERMAID_STATE_CHOICE)
|| rest_low.contains(MERMAID_STATE_CHOICE_ALT)
{
let id: String = rest
.split_whitespace()
.next()
.unwrap_or("")
.trim()
.to_string();
if !id.is_empty() {
upsert_state_node(
&mut chart,
id.clone(),
id,
MermaidNodeShape::Diamond,
sg_stack.last().copied(),
);
}
continue;
}
if let Some((lhs, rhs)) = rest.split_once(MERMAID_ALIAS_SEP) {
let text_value: String = lhs.trim().trim_matches('"').to_string();
let id: String = rhs.trim().to_string();
upsert_state_node(
&mut chart,
id,
text_value,
MermaidNodeShape::Rounded,
sg_stack.last().copied(),
);
continue;
}
}
let active_sg: Option<usize> = sg_stack.last().copied();
if let Some((edge_part, lbl_part)) = line.split_once(':')
&& edge_part.contains("-->")
{
let (from_raw, to_raw): (&str, &str) = edge_part.split_once("-->").unwrap_or(("", ""));
let from_id: String = register_state_node(
&mut chart,
from_raw.trim(),
true,
active_sg,
&mut terminal_counter,
);
let to_id: String = register_state_node(
&mut chart,
to_raw.trim(),
false,
active_sg,
&mut terminal_counter,
);
chart.get_mut_edges().push(MermaidFlowEdge::new(
from_id,
to_id,
lbl_part.trim().to_string(),
MermaidEdgeStyle::Solid,
));
} else if let Some((from_raw, to_raw)) = line.split_once("-->") {
let from_id: String = register_state_node(
&mut chart,
from_raw.trim(),
true,
active_sg,
&mut terminal_counter,
);
let to_id: String = register_state_node(
&mut chart,
to_raw.trim(),
false,
active_sg,
&mut terminal_counter,
);
chart.get_mut_edges().push(MermaidFlowEdge::new(
from_id,
to_id,
String::new(),
MermaidEdgeStyle::Solid,
));
}
}
chart
}
fn upsert_state_node(
chart: &mut MermaidFlowchart,
id: String,
label: String,
shape: MermaidNodeShape,
subgraph: Option<usize>,
) {
if let Some(existing) = chart
.get_mut_nodes()
.iter_mut()
.find(|item_count: &&mut MermaidFlowNode| item_count.get_id().as_str() == id.as_str())
{
existing.set_label(label);
existing.set_shape(shape);
if existing.get_subgraph().is_none() && subgraph.is_some() {
existing.set_subgraph(subgraph);
}
return;
}
chart
.get_mut_nodes()
.push(MermaidFlowNode::new(id, label, shape, subgraph));
}
fn attach_state_note(
chart: &mut MermaidFlowchart,
target_id: &str,
text: String,
subgraph: Option<usize>,
note_counter: &mut usize,
) {
if target_id.is_empty() || text.is_empty() {
return;
}
*note_counter += 1;
let nid: String = format!("__note_{}", *note_counter);
chart.get_mut_nodes().push(MermaidFlowNode::new(
nid.clone(),
text,
MermaidNodeShape::Note,
subgraph,
));
chart.get_mut_edges().push(MermaidFlowEdge::new(
target_id.to_string(),
nid,
String::new(),
MermaidEdgeStyle::DashedPlain,
));
}
fn register_state_node(
chart: &mut MermaidFlowchart,
raw: &str,
is_start: bool,
subgraph: Option<usize>,
terminal_counter: &mut usize,
) -> String {
if raw == MERMAID_STATE_TERMINAL {
*terminal_counter += 1;
let id: String = if is_start {
format!("__start_{}", *terminal_counter)
} else {
format!("__end_{}", *terminal_counter)
};
let shape: MermaidNodeShape = if is_start {
MermaidNodeShape::StateStart
} else {
MermaidNodeShape::StateEnd
};
chart.get_mut_nodes().push(MermaidFlowNode::new(
id.clone(),
String::new(),
shape,
subgraph,
));
return id;
}
if let Some(existing) = chart
.get_mut_nodes()
.iter_mut()
.find(|item_count: &&mut MermaidFlowNode| item_count.get_id().as_str() == raw)
{
if existing.get_subgraph().is_none() && subgraph.is_some() {
existing.set_subgraph(subgraph);
}
return raw.to_string();
}
chart.get_mut_nodes().push(MermaidFlowNode::new(
raw.to_string(),
raw.to_string(),
MermaidNodeShape::Rounded,
subgraph,
));
raw.to_string()
}
fn parse_mermaid_class(lines: &[&str]) -> MermaidClassDiagram {
let mut diag: MermaidClassDiagram = MermaidClassDiagram::default();
let mut active_class: Option<usize> = None;
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
if line == "}" {
active_class = None;
continue;
}
if let Some(cls_idx) = active_class {
if line.starts_with("<<") && line.ends_with(">>") {
diag.get_mut_classes()[cls_idx].set_stereotype(line.to_string());
} else {
diag.get_mut_classes()[cls_idx]
.get_mut_members()
.push(line.to_string());
}
continue;
}
if line.starts_with("<<")
&& let Some(end_st) = line.find(">>")
{
let stereo: &str = &line[..end_st + 2];
let cls_name: &str = line[end_st + 2..].trim();
if !cls_name.is_empty() {
let idx: usize = ensure_class_box(&mut diag, cls_name);
diag.get_mut_classes()[idx].set_stereotype(stereo.to_string());
continue;
}
}
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_CLASS_DECL) {
let rest: &str = line[MERMAID_KW_CLASS_DECL.len()..].trim();
let opens_block: bool = rest.ends_with('{');
let body_hdr: &str = rest.trim_end_matches('{').trim();
let (name, inline_stereo): (&str, Option<&str>) = if let Some(st_pos) =
body_hdr.find("<<")
&& let Some(end_pos) = body_hdr[st_pos..].find(">>")
{
(
body_hdr[..st_pos].trim(),
Some(&body_hdr[st_pos..st_pos + end_pos + 2]),
)
} else {
(body_hdr, None)
};
let idx: usize = ensure_class_box(&mut diag, name);
if let Some(stereo) = inline_stereo {
diag.get_mut_classes()[idx].set_stereotype(stereo.to_string());
}
if opens_block {
active_class = Some(idx);
}
continue;
}
let rel_ops: [(&str, MermaidEdgeStyle, MermaidClassRelKind, bool); 14] = [
(
"<|--",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Inheritance,
false,
),
(
"--|>",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Inheritance,
true,
),
(
"<|..",
MermaidEdgeStyle::Dashed,
MermaidClassRelKind::Realization,
false,
),
(
"..|>",
MermaidEdgeStyle::Dashed,
MermaidClassRelKind::Realization,
true,
),
(
"*--",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Composition,
false,
),
(
"--*",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Composition,
true,
),
(
"o--",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Aggregation,
false,
),
(
"--o",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Aggregation,
true,
),
(
"-->",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Association,
false,
),
(
"<--",
MermaidEdgeStyle::Solid,
MermaidClassRelKind::Association,
true,
),
(
"..>",
MermaidEdgeStyle::Dashed,
MermaidClassRelKind::Dependency,
false,
),
(
"<..",
MermaidEdgeStyle::Dashed,
MermaidClassRelKind::Dependency,
true,
),
(
"--",
MermaidEdgeStyle::Plain,
MermaidClassRelKind::Link,
false,
),
(
"..",
MermaidEdgeStyle::DashedPlain,
MermaidClassRelKind::Link,
false,
),
];
let mut matched_rel: bool = false;
for (op, style, kind, swap_dir) in rel_ops.into_iter() {
if let Some(pos) = line.find(op) {
let lhs_raw: &str = line[..pos].trim();
let rhs_all: &str = line[pos + op.len()..].trim();
let (rhs_raw, text_value): (&str, &str) = match rhs_all.split_once(':') {
Some((red_val, line_item)) => (red_val.trim(), line_item.trim()),
None => (rhs_all, ""),
};
let lhs: &str = lhs_raw.split_whitespace().next().unwrap_or("");
let rhs: &str = rhs_raw.split_whitespace().last().unwrap_or("");
if !lhs.is_empty() && !rhs.is_empty() {
let _: usize = ensure_class_box(&mut diag, lhs);
let _: usize = ensure_class_box(&mut diag, rhs);
let (from, to): (&str, &str) = if swap_dir { (rhs, lhs) } else { (lhs, rhs) };
let mut rel: MermaidClassRelation = MermaidClassRelation::new(
from.to_string(),
to.to_string(),
text_value.to_string(),
style,
);
rel.set_rel_kind(kind);
diag.get_mut_relations().push(rel);
matched_rel = true;
}
break;
}
}
if !matched_rel && let Some((cls_name, member)) = line.split_once(':') {
let idx: usize = ensure_class_box(&mut diag, cls_name.trim());
diag.get_mut_classes()[idx]
.get_mut_members()
.push(member.trim().to_string());
}
}
diag
}
fn ensure_class_box(diag: &mut MermaidClassDiagram, name: &str) -> usize {
if let Some(pos) = diag
.get_classes()
.iter()
.position(|char_item: &MermaidClassBox| char_item.get_name().as_str() == name)
{
return pos;
}
let idx: usize = diag.get_classes().len();
diag.get_mut_classes()
.push(MermaidClassBox::new(name.to_string(), Vec::new()));
idx
}
fn parse_mermaid_er(lines: &[&str]) -> MermaidErDiagram {
let mut diag: MermaidErDiagram = MermaidErDiagram::default();
let mut active_ent: Option<usize> = None;
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
if line == "}" {
active_ent = None;
continue;
}
if let Some(ent_idx) = active_ent {
diag.get_mut_entities()[ent_idx]
.get_mut_attributes()
.push(line.to_string());
continue;
}
if line.ends_with('{') && !line.contains("--") && !line.contains("..") {
let name: &str = line.trim_end_matches('{').trim();
if !name.is_empty() {
active_ent = Some(ensure_er_entity(&mut diag, name));
}
continue;
}
let (sep_pos_opt, dashed): (Option<usize>, bool) = if let Some(point_val) = line.find("--")
{
(Some(point_val), false)
} else if let Some(palette_val) = line.find("..") {
(Some(palette_val), true)
} else {
(None, false)
};
if let Some(dash_pos) = sep_pos_opt {
let left_side: &str = line[..dash_pos].trim();
let right_side: &str = line[dash_pos + 2..].trim();
let (left_ent, left_card): (&str, &str) = match left_side.rsplit_once(' ') {
Some((event_ref, char_item)) => (event_ref.trim(), char_item.trim()),
None => (left_side, "||"),
};
let (right_part, text_value): (&str, &str) = match right_side.split_once(':') {
Some((red_val, line_item)) => (red_val.trim(), line_item.trim().trim_matches('"')),
None => (right_side, ""),
};
let (right_card, right_ent): (&str, &str) = match right_part.split_once(' ') {
Some((color_item, error_val)) => (color_item.trim(), error_val.trim()),
None => ("o{", right_part),
};
if !left_ent.is_empty() && !right_ent.is_empty() {
let _: usize = ensure_er_entity(&mut diag, left_ent);
let _: usize = ensure_er_entity(&mut diag, right_ent);
let mut rel: MermaidErRelation = MermaidErRelation::new(
left_ent.to_string(),
right_ent.to_string(),
left_card.to_string(),
right_card.to_string(),
text_value.to_string(),
);
rel.set_dashed(dashed);
diag.get_mut_relations().push(rel);
}
}
}
diag
}
fn ensure_er_entity(diag: &mut MermaidErDiagram, name: &str) -> usize {
if let Some(pos) = diag
.get_entities()
.iter()
.position(|event_ref: &MermaidErEntity| event_ref.get_name().as_str() == name)
{
return pos;
}
let idx: usize = diag.get_entities().len();
diag.get_mut_entities()
.push(MermaidErEntity::new(name.to_string(), Vec::new()));
idx
}
fn parse_mermaid_pie(lines: &[&str]) -> MermaidPieChart {
let mut chart: MermaidPieChart = MermaidPieChart::default();
if let Some(first) = lines.first() {
let low: String = first.to_ascii_lowercase();
if let Some(t_pos) = low.find(MERMAID_KW_TITLE) {
chart.set_title(first[t_pos + MERMAID_KW_TITLE.len()..].trim().to_string());
}
}
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_TITLE) {
chart.set_title(line[MERMAID_KW_TITLE.len()..].trim().to_string());
continue;
}
if let Some((lbl_raw, val_raw)) = line.split_once(':') {
let text_value: String = lbl_raw.trim().trim_matches('"').to_string();
if let Ok(val) = val_raw.trim().parse::<f32>()
&& val > 0.0
{
chart
.get_mut_slices()
.push(MermaidPieSlice::new(text_value, val));
}
}
}
chart
}
fn parse_mermaid_gantt(lines: &[&str]) -> MermaidGanttChart {
let mut chart: MermaidGanttChart = MermaidGanttChart::default();
let mut current_section: String = MERMAID_DEFAULT_SECTION.to_string();
let mut cursor_unit: f32 = 0.0;
let mut task_ends: HashMap<String, f32> = HashMap::new();
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_TITLE) {
chart.set_title(line[MERMAID_KW_TITLE.len()..].trim().to_string());
continue;
}
if low.starts_with(MERMAID_KW_SECTION) {
current_section = line[MERMAID_KW_SECTION.len()..].trim().to_string();
continue;
}
if low.starts_with(MERMAID_KW_DATE_FORMAT) || low.starts_with(MERMAID_KW_AXIS_FORMAT) {
continue;
}
if let Some((label_raw, meta_raw)) = line.split_once(':') {
let label: String = label_raw.trim().to_string();
let mut status: MermaidGanttStatus = MermaidGanttStatus::Normal;
let mut dur: f32 = 3.0;
let mut start_u: f32 = cursor_unit;
let mut task_id: Option<String> = None;
for part in meta_raw.split(',') {
let text_value: &str = part.trim();
let p_low: String = text_value.to_ascii_lowercase();
if p_low == MERMAID_GANTT_DONE {
status = MermaidGanttStatus::Done;
} else if p_low == MERMAID_GANTT_ACTIVE {
status = MermaidGanttStatus::Active;
} else if p_low == MERMAID_GANTT_CRIT {
status = MermaidGanttStatus::Critical;
} else if p_low == MERMAID_GANTT_MILESTONE {
status = MermaidGanttStatus::Milestone;
dur = 1.0;
} else if let Some(after_id) = p_low.strip_prefix("after ") {
if let Some(&dep_end) = task_ends.get(after_id.trim()) {
start_u = dep_end;
}
} else if let Some(d_str) = p_low.strip_suffix('d')
&& let Ok(days) = d_str.parse::<f32>()
{
dur = days.clamp(0.5, 30.0);
} else if let Some(w_str) = p_low.strip_suffix('w')
&& let Ok(weeks) = w_str.parse::<f32>()
{
dur = (weeks * 7.0).clamp(1.0, 35.0);
} else if let Some(h_str) = p_low.strip_suffix('h')
&& let Ok(hours) = h_str.parse::<f32>()
{
dur = (hours / 24.0).clamp(0.5, 30.0);
} else if task_id.is_none()
&& !text_value.is_empty()
&& !text_value.contains('-')
&& text_value.bytes().all(|blue_val: u8| {
blue_val.is_ascii_alphanumeric() || blue_val == MERMAID_BYTE_UNDERSCORE
})
{
task_id = Some(p_low);
}
}
if let Some(tid) = task_id {
let _: Option<f32> = task_ends.insert(tid, start_u + dur);
}
chart.get_mut_tasks().push(MermaidGanttTask::new(
current_section.clone(),
label,
status,
start_u,
dur,
));
cursor_unit = (start_u + (dur * 0.72).max(1.5)).max(cursor_unit);
}
}
chart
}
fn parse_mermaid_timeline(lines: &[&str]) -> MermaidTimeline {
let mut tl: MermaidTimeline = MermaidTimeline::default();
let mut current_section: String = String::new();
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_TITLE) {
tl.set_title(line[MERMAID_KW_TITLE.len()..].trim().to_string());
continue;
}
if low.starts_with(MERMAID_KW_SECTION) {
current_section = line[MERMAID_KW_SECTION.len()..].trim().to_string();
continue;
}
if let Some(rest) = line.strip_prefix(':') {
let item: String = rest.trim().to_string();
if !item.is_empty()
&& let Some(last) = tl.get_mut_events().last_mut()
{
last.get_mut_items().push(item);
}
continue;
}
if let Some((period, events_part)) = line.split_once(':') {
let items: Vec<String> = events_part
.split(':')
.map(|text_value: &str| text_value.trim().to_string())
.filter(|label_str: &String| !label_str.is_empty())
.collect();
tl.get_mut_events().push(MermaidTimelineEvent::new(
current_section.clone(),
period.trim().to_string(),
items,
));
} else if !line.is_empty() {
tl.get_mut_events().push(MermaidTimelineEvent::new(
current_section.clone(),
line.to_string(),
Vec::new(),
));
}
}
tl
}
fn parse_mermaid_mindmap(raw_lines: &[&str]) -> MermaidMindmap {
let mut mm: MermaidMindmap = MermaidMindmap::default();
let mut indent_stack: Vec<usize> = Vec::new();
for raw in raw_lines.iter().skip(1) {
let trimmed: &str = raw.trim();
if trimmed.is_empty() || trimmed.starts_with("::icon(") || trimmed.starts_with(":::") {
continue;
}
let indent: usize = raw
.bytes()
.take_while(|blue_val: &u8| *blue_val == b' ' || *blue_val == b'\t')
.map(|byte_val: u8| if byte_val == b'\t' { 2 } else { 1 })
.sum();
while let Some(&top) = indent_stack.last() {
if indent <= top {
let _: Option<usize> = indent_stack.pop();
} else {
break;
}
}
let depth: usize = indent_stack.len();
indent_stack.push(indent);
let (_, label, shape, _, _): (String, String, MermaidNodeShape, bool, Vec<String>) =
parse_flow_node_token(trimmed);
let clean_lbl: String = label.trim().to_string();
if !clean_lbl.is_empty() {
mm.get_mut_nodes()
.push(MermaidMindmapNode::new(clean_lbl, depth, shape));
}
}
mm
}
fn parse_bracket_list(line: &str) -> Vec<String> {
let Some(lb) = line.find('[') else {
return Vec::new();
};
let Some(rb) = line.rfind(']') else {
return Vec::new();
};
if rb <= lb {
return Vec::new();
}
line[lb + 1..rb]
.split(',')
.map(|text_value: &str| {
text_value
.trim()
.trim_matches('"')
.trim_matches('\'')
.to_string()
})
.filter(|label_str: &String| !label_str.is_empty())
.collect()
}
fn parse_mermaid_xychart(lines: &[&str]) -> MermaidXyChart {
let mut xy: MermaidXyChart = MermaidXyChart::default();
let mut has_y_bounds: bool = false;
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_TITLE) {
xy.set_title(
line[MERMAID_KW_TITLE.len()..]
.trim()
.trim_matches('"')
.to_string(),
);
continue;
}
if low.starts_with(MERMAID_KW_X_AXIS) {
let labels: Vec<String> = parse_bracket_list(line);
if !labels.is_empty() {
xy.set_x_labels(labels);
}
continue;
}
if low.starts_with(MERMAID_KW_Y_AXIS) {
let rest: &str = line[MERMAID_KW_Y_AXIS.len()..].trim();
if let Some(q1) = rest.find('"')
&& let Some(q2) = rest[q1 + 1..].find('"')
{
xy.set_y_label(rest[q1 + 1..q1 + 1 + q2].to_string());
let after_q: &str = rest[q1 + 1 + q2 + 1..].trim();
if let Some((min_s, max_s)) = after_q.split_once("-->")
&& let (Ok(lo), Ok(hi)) =
(min_s.trim().parse::<f32>(), max_s.trim().parse::<f32>())
{
xy.set_y_min(lo).set_y_max(hi);
has_y_bounds = true;
}
} else if let Some((min_s, max_s)) = rest.split_once("-->")
&& let (Ok(lo), Ok(hi)) = (min_s.trim().parse::<f32>(), max_s.trim().parse::<f32>())
{
xy.set_y_min(lo).set_y_max(hi);
has_y_bounds = true;
}
continue;
}
if low.starts_with(MERMAID_KW_BAR) || low.starts_with(MERMAID_KW_LINE) {
let is_bar: bool = low.starts_with(MERMAID_KW_BAR);
let values: Vec<f32> = parse_bracket_list(line)
.into_iter()
.filter_map(|text_value: String| text_value.parse::<f32>().ok())
.collect();
if !values.is_empty() {
xy.get_mut_series()
.push(MermaidXySeries::new(is_bar, values));
}
}
}
if !has_y_bounds {
let mut lo: f32 = 0.0;
let mut hi: f32 = 10.0;
for ser in xy.get_series().iter() {
for &item_val in ser.get_values().iter() {
lo = lo.min(item_val);
hi = hi.max(item_val);
}
}
if (hi - lo).abs() < 0.001 {
hi = lo + 10.0;
}
xy.set_y_min(lo).set_y_max(hi);
}
if xy.get_x_labels().is_empty() {
let max_len: usize = xy
.get_series()
.iter()
.map(|source_val: &MermaidXySeries| source_val.get_values().len())
.max()
.unwrap_or(0);
let fallback: Vec<String> = (1..=max_len)
.map(|item_index: usize| item_index.to_string())
.collect();
xy.set_x_labels(fallback);
}
xy
}
fn extract_git_attr(line: &str, key: &str) -> Option<String> {
let low: String = line.to_ascii_lowercase();
let pos: usize = low.find(key)?;
let rest: &str = line[pos + key.len()..].trim_start();
if let Some(after_q) = rest.strip_prefix('"') {
let end_q: usize = after_q.find('"').unwrap_or(after_q.len());
return Some(after_q[..end_q].to_string());
}
rest.split_whitespace().next().map(str::to_string)
}
fn parse_mermaid_gitgraph(lines: &[&str]) -> MermaidGitGraph {
let mut git: MermaidGitGraph = MermaidGitGraph::default();
git.get_mut_branches().push(MERMAID_GIT_MAIN.to_string());
let mut active_branch: usize = 0;
let mut branch_heads: HashMap<usize, usize> = HashMap::new();
let mut commit_seq: usize = 0;
for raw in lines.iter().skip(1) {
let line: &str = raw.trim();
let low: String = line.to_ascii_lowercase();
if low.starts_with(MERMAID_KW_BRANCH) {
let name: String = line[MERMAID_KW_BRANCH.len()..]
.split_whitespace()
.next()
.unwrap_or("")
.trim_matches('"')
.to_string();
if !name.is_empty() {
let parent_head: Option<usize> = branch_heads.get(&active_branch).copied();
let lane: usize = ensure_git_branch(&mut git, &name);
if let Some(ph) = parent_head {
let _: &mut usize = branch_heads.entry(lane).or_insert(ph);
}
active_branch = lane;
}
continue;
}
if low.starts_with(MERMAID_KW_CHECKOUT) || low.starts_with(MERMAID_KW_SWITCH) {
let prefix_len: usize = if low.starts_with(MERMAID_KW_CHECKOUT) {
MERMAID_KW_CHECKOUT.len()
} else {
MERMAID_KW_SWITCH.len()
};
let name: &str = line[prefix_len..]
.split_whitespace()
.next()
.unwrap_or("")
.trim_matches('"');
if !name.is_empty() {
active_branch = ensure_git_branch(&mut git, name);
}
continue;
}
if low.starts_with(MERMAID_KW_MERGE) {
let src_name: &str = line[MERMAID_KW_MERGE.len()..]
.split_whitespace()
.next()
.unwrap_or("")
.trim_matches('"');
let src_lane: usize = ensure_git_branch(&mut git, src_name);
commit_seq += 1;
let id: String = extract_git_attr(line, MERMAID_GIT_KEY_ID)
.unwrap_or_else(|| format!("M{commit_seq}"));
let tag: String = extract_git_attr(line, MERMAID_GIT_KEY_TAG).unwrap_or_default();
let ctype: String = extract_git_attr(line, MERMAID_GIT_KEY_TYPE).unwrap_or_default();
let parent_idx: Option<usize> = branch_heads.get(&active_branch).copied();
let idx: usize = git.get_commits().len();
let b_name: String = git.get_branches()[active_branch].clone();
git.get_mut_commits().push(MermaidGitCommit::new(
id,
b_name,
active_branch,
tag,
ctype,
Some(src_lane),
parent_idx,
));
let _: Option<usize> = branch_heads.insert(active_branch, idx);
continue;
}
if low.starts_with(MERMAID_KW_COMMIT) || low.starts_with(MERMAID_KW_CHERRY_PICK) {
commit_seq += 1;
let id: String = extract_git_attr(line, MERMAID_GIT_KEY_ID)
.unwrap_or_else(|| format!("C{commit_seq}"));
let tag: String = extract_git_attr(line, MERMAID_GIT_KEY_TAG).unwrap_or_default();
let ctype: String = extract_git_attr(line, MERMAID_GIT_KEY_TYPE).unwrap_or_default();
let parent_idx: Option<usize> = branch_heads.get(&active_branch).copied();
let idx: usize = git.get_commits().len();
let b_name: String = git.get_branches()[active_branch].clone();
git.get_mut_commits().push(MermaidGitCommit::new(
id,
b_name,
active_branch,
tag,
ctype,
None,
parent_idx,
));
let _: Option<usize> = branch_heads.insert(active_branch, idx);
}
}
git
}
fn ensure_git_branch(git: &mut MermaidGitGraph, name: &str) -> usize {
if let Some(pos) = git
.get_branches()
.iter()
.position(|text_value: &String| text_value.as_str() == name)
{
return pos;
}
let idx: usize = git.get_branches().len();
git.get_mut_branches().push(name.to_string());
idx
}
fn dfs_collect_dag_edges(
tex_u: usize,
adj: &[Vec<usize>],
state: &mut [u8],
dag_edges: &mut Vec<(usize, usize)>,
) {
state[tex_u] = 1;
for &item_val in adj[tex_u].iter() {
if tex_u == item_val || state[item_val] == 1 {
continue;
}
dag_edges.push((tex_u, item_val));
if state[item_val] == 0 {
dfs_collect_dag_edges(item_val, adj, state, dag_edges);
}
}
state[tex_u] = 2;
}
fn compute_flowchart_dag_layers(
fc: &MermaidFlowchart,
id_map: &HashMap<&str, usize>,
) -> Vec<usize> {
let item_count: usize = fc.get_nodes().len();
let mut adj: Vec<Vec<usize>> = vec![Vec::new(); item_count];
let mut in_deg: Vec<usize> = vec![0; item_count];
for edge in fc.get_edges().iter() {
if let (Some(&tex_u), Some(&item_val)) = (
id_map.get(edge.get_from().as_str()),
id_map.get(edge.get_to().as_str()),
) && tex_u != item_val
{
adj[tex_u].push(item_val);
in_deg[item_val] += 1;
}
}
let mut state: Vec<u8> = vec![0; item_count];
let mut dag_edges: Vec<(usize, usize)> = Vec::with_capacity(fc.get_edges().len());
for (idx, node) in fc.get_nodes().iter().enumerate() {
if node.get_shape() == MermaidNodeShape::StateStart && state[idx] == 0 {
dfs_collect_dag_edges(idx, &adj, &mut state, &mut dag_edges);
}
}
for (idx, node) in fc.get_nodes().iter().enumerate() {
if in_deg[idx] == 0 && node.get_shape() != MermaidNodeShape::StateEnd && state[idx] == 0 {
dfs_collect_dag_edges(idx, &adj, &mut state, &mut dag_edges);
}
}
for idx in 0..item_count {
if state[idx] == 0 {
dfs_collect_dag_edges(idx, &adj, &mut state, &mut dag_edges);
}
}
let mut layers: Vec<usize> = vec![0; item_count];
for _ in 0..item_count {
let mut changed: bool = false;
for &(bary_u, tex_v) in dag_edges.iter() {
if layers[tex_v] <= layers[bary_u] && layers[bary_u] + 1 < item_count {
layers[tex_v] = layers[bary_u] + 1;
changed = true;
}
}
if !changed {
break;
}
}
for edge in fc.get_edges().iter() {
if let (Some(&unit_u), Some(&bary_v)) = (
id_map.get(edge.get_from().as_str()),
id_map.get(edge.get_to().as_str()),
) && unit_u != bary_v
&& fc.get_nodes()[bary_v].get_shape() == MermaidNodeShape::StateEnd
&& layers[bary_v] <= layers[unit_u]
{
layers[bary_v] = layers[unit_u] + 1;
}
}
layers
}
fn layout_flowchart_nodes(fc: &MermaidFlowchart) -> (Vec<Rect>, Size) {
let item_count: usize = fc.get_nodes().len();
if item_count == 0 {
return (Vec::new(), Size::new(360.0, 140.0));
}
let mut id_map: HashMap<&str, usize> = HashMap::with_capacity(item_count);
for (idx, node) in fc.get_nodes().iter().enumerate() {
let _: Option<usize> = id_map.insert(node.get_id().as_str(), idx);
}
let layers: Vec<usize> = compute_flowchart_dag_layers(fc, &id_map);
let max_layer: usize = layers.iter().copied().max().unwrap_or(0);
let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); max_layer + 1];
for (idx, &lay) in layers.iter().enumerate() {
buckets[lay].push(idx);
}
let horiz: bool = matches!(
fc.get_direction(),
MermaidFlowDirection::LeftRight | MermaidFlowDirection::RightLeft
);
let reversed: bool = matches!(
fc.get_direction(),
MermaidFlowDirection::RightLeft | MermaidFlowDirection::BottomTop
);
let node_sizes: Vec<(f32, f32)> = fc
.get_nodes()
.iter()
.map(|node: &MermaidFlowNode| {
let chars: f32 = node.get_label().chars().count() as f32;
match node.get_shape() {
MermaidNodeShape::StateStart | MermaidNodeShape::StateEnd => (24.0, 24.0),
MermaidNodeShape::ForkJoin => (96.0, 10.0),
MermaidNodeShape::Circle | MermaidNodeShape::DoubleCircle => {
let delta_val: f32 = (chars * 7.8 + 30.0).clamp(52.0, 104.0);
(delta_val, delta_val)
}
MermaidNodeShape::Diamond => ((chars * 8.2 + 48.0).clamp(108.0, 196.0), 60.0),
MermaidNodeShape::Hexagon => ((chars * 7.8 + 52.0).clamp(112.0, 210.0), 44.0),
MermaidNodeShape::Cylinder => ((chars * 7.8 + 38.0).clamp(100.0, 210.0), 50.0),
MermaidNodeShape::Parallelogram
| MermaidNodeShape::ParallelogramAlt
| MermaidNodeShape::Trapezoid
| MermaidNodeShape::TrapezoidAlt
| MermaidNodeShape::Asymmetric => ((chars * 7.8 + 48.0).clamp(112.0, 216.0), 42.0),
MermaidNodeShape::Subroutine => ((chars * 7.8 + 46.0).clamp(108.0, 216.0), 42.0),
MermaidNodeShape::Note => ((chars * 7.2 + 30.0).clamp(110.0, 220.0), 36.0),
_ => ((chars * 7.8 + 34.0).clamp(96.0, 210.0), 40.0),
}
})
.collect();
let has_labels: bool = fc
.get_edges()
.iter()
.any(|edge: &MermaidFlowEdge| !edge.get_label().is_empty());
let mut bidir_label_w: f32 = 0.0;
for edge in fc.get_edges().iter() {
if let (Some(&tex_u), Some(&item_val)) = (
id_map.get(edge.get_from().as_str()),
id_map.get(edge.get_to().as_str()),
) && tex_u != item_val
&& fc.get_edges().iter().any(|other: &MermaidFlowEdge| {
id_map.get(other.get_from().as_str()) == Some(&item_val)
&& id_map.get(other.get_to().as_str()) == Some(&tex_u)
})
{
let lbl_w: f32 = ((edge.get_label().chars().count() as f32) * 6.8 + 14.0).max(34.0);
bidir_label_w = bidir_label_w.max(lbl_w);
}
}
let sg_pad: f32 = if fc.get_subgraphs().is_empty() {
0.0
} else {
20.0
};
let pad: f32 = 34.0 + sg_pad;
let cross_pad: f32 = if !horiz && bidir_label_w > 0.0 {
(bidir_label_w + 36.0).max(pad)
} else if horiz && bidir_label_w > 0.0 {
56.0 + sg_pad
} else {
pad
};
let main_gap: f32 = if has_labels {
if horiz { 82.0 } else { 88.0 }
} else if horiz {
58.0
} else {
50.0
};
let cross_gap: f32 = if !horiz && bidir_label_w > 0.0 {
(bidir_label_w + 48.0).max(30.0)
} else {
30.0
};
let layer_count: usize = buckets.len();
let mut layer_main_dim: Vec<f32> = vec![0.0; layer_count];
let mut layer_cross_span: Vec<f32> = vec![0.0; layer_count];
for (l_idx, items) in buckets.iter().enumerate() {
let mut max_main: f32 = 0.0;
let mut sum_cross: f32 = 0.0;
for (pos, &ni) in items.iter().enumerate() {
let (nw, nh): (f32, f32) = node_sizes[ni];
if horiz {
max_main = max_main.max(nw);
sum_cross += nh;
} else {
max_main = max_main.max(nh);
sum_cross += nw;
}
if pos + 1 < items.len() {
sum_cross += cross_gap;
}
}
layer_main_dim[l_idx] = max_main;
layer_cross_span[l_idx] = sum_cross;
}
let total_main: f32 =
layer_main_dim.iter().sum::<f32>() + (layer_count.saturating_sub(1) as f32) * main_gap;
let total_cross: f32 = layer_cross_span.iter().copied().fold(0.0_f32, f32::max);
let mut rects: Vec<Rect> = vec![Rect::default(); item_count];
let mut main_cursor: f32 = pad;
let layer_order: Vec<usize> = if reversed {
(0..layer_count).rev().collect()
} else {
(0..layer_count).collect()
};
for l_idx in layer_order.into_iter() {
let items: &[usize] = &buckets[l_idx];
let band_main: f32 = layer_main_dim[l_idx];
let band_cross: f32 = layer_cross_span[l_idx];
let mut cross_cursor: f32 = cross_pad + (total_cross - band_cross) * 0.5;
for &ni in items.iter() {
let (nw, nh): (f32, f32) = node_sizes[ni];
let rect_bounds: Rect = if horiz {
let rx: f32 = main_cursor + (band_main - nw) * 0.5;
let ry: f32 = cross_cursor;
cross_cursor += nh + cross_gap;
Rect::new(rx, ry, nw, nh)
} else {
let rx: f32 = cross_cursor;
let ry: f32 = main_cursor + (band_main - nh) * 0.5;
cross_cursor += nw + cross_gap;
Rect::new(rx, ry, nw, nh)
};
rects[ni] = rect_bounds;
}
main_cursor += band_main + main_gap;
}
let (width_val, height_val): (f32, f32) = if horiz {
(
(total_main + pad * 2.0).max(360.0),
(total_cross + cross_pad * 2.0).max(160.0),
)
} else {
(
(total_cross + cross_pad * 2.0).max(360.0),
(total_main + pad * 2.0).max(160.0),
)
};
(rects, Size::new(width_val, height_val))
}
fn measure_flowchart(fc: &MermaidFlowchart) -> Size {
let (_, sz): (Vec<Rect>, Size) = layout_flowchart_nodes(fc);
sz
}
fn subgraph_contains(
subgraphs: &[MermaidSubgraph],
node_sg: Option<usize>,
target_sg: usize,
) -> bool {
let mut cur: Option<usize> = node_sg;
let mut guard: usize = 0;
while let Some(idx) = cur {
if idx == target_sg {
return true;
}
guard += 1;
if guard > subgraphs.len() {
break;
}
cur = subgraphs
.get(idx)
.and_then(|source_val: &MermaidSubgraph| source_val.get_parent());
}
false
}
fn subgraph_depth(subgraphs: &[MermaidSubgraph], idx: usize) -> usize {
let mut depth: usize = 0;
let mut cur: Option<usize> = subgraphs
.get(idx)
.and_then(|source_val: &MermaidSubgraph| source_val.get_parent());
while let Some(parent_idx) = cur {
depth += 1;
if depth > subgraphs.len() {
break;
}
cur = subgraphs
.get(parent_idx)
.and_then(|scale_val: &MermaidSubgraph| scale_val.get_parent());
}
depth
}
fn rects_overlap_padded(rect_bounds: Rect, clip_bounds: Rect, pad: f32) -> bool {
rect_bounds.get_x() - pad < clip_bounds.right()
&& rect_bounds.right() + pad > clip_bounds.get_x()
&& rect_bounds.get_y() - pad < clip_bounds.bottom()
&& rect_bounds.bottom() + pad > clip_bounds.get_y()
}
fn edge_pill_collides(cand: Rect, placed_pills: &[Rect], node_rects: &[Rect]) -> bool {
placed_pills
.iter()
.any(|rect_bounds: &Rect| rects_overlap_padded(cand, *rect_bounds, 4.0))
|| node_rects
.iter()
.any(|nr: &Rect| rects_overlap_padded(cand, *nr, 2.0))
}
fn resolve_edge_pill_rect(
p0: Point,
p1: Point,
base_pill: Rect,
placed_pills: &[Rect],
node_rects: &[Rect],
) -> Rect {
if !edge_pill_collides(base_pill, placed_pills, node_rects) {
return base_pill;
}
let pw: f32 = base_pill.get_width();
let ph: f32 = base_pill.get_height();
let dx: f32 = p1.get_x() - p0.get_x();
let dy: f32 = p1.get_y() - p0.get_y();
let fractions: [f32; 6] = [0.78, 0.22, 0.72, 0.28, 0.84, 0.16];
for blend_factor in fractions.into_iter() {
let cx: f32 = p0.get_x() + dx * blend_factor;
let cy: f32 = p0.get_y() + dy * blend_factor;
let variants: [Rect; 3] = [
Rect::new(cx - pw * 0.5, cy - ph * 0.5, pw, ph),
Rect::new(cx + 8.0, cy - ph * 0.5, pw, ph),
Rect::new(cx - pw - 8.0, cy - ph * 0.5, pw, ph),
];
for cand in variants.into_iter() {
if !edge_pill_collides(cand, placed_pills, node_rects) {
return cand;
}
}
}
let mut shifted: Rect = base_pill;
for _ in 0..6 {
let blocker: Option<Rect> = placed_pills
.iter()
.copied()
.find(|rect_bounds: &Rect| rects_overlap_padded(shifted, *rect_bounds, 4.0));
if let Some(other) = blocker {
shifted = Rect::new(other.right() + 6.0, shifted.get_y(), pw, ph);
} else {
break;
}
}
shifted
}
fn draw_polygon(
display_list: &mut DisplayList,
pts: &[Point],
fill: Color,
stroke: Color,
width: f32,
) {
if pts.len() < 3 {
return;
}
for idx in 1..(pts.len() - 1) {
display_list.push(DrawCommand::Triangle {
p0: pts[0],
p1: pts[idx],
p2: pts[idx + 1],
color: fill,
});
}
for idx in 0..pts.len() {
let next: Point = pts[(idx + 1) % pts.len()];
display_list.push(DrawCommand::Line {
from: pts[idx],
to: next,
color: stroke,
width,
});
}
}
fn draw_flowchart(
fc: &MermaidFlowchart,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let (local_rects, nat_sz): (Vec<Rect>, Size) = layout_flowchart_nodes(fc);
let ox: f32 = bounds.get_x() + ((bounds.get_width() - nat_sz.get_width()).max(0.0)) * 0.5;
let oy: f32 = bounds.get_y() + ((bounds.get_height() - nat_sz.get_height()).max(0.0)) * 0.5;
let rects: Vec<Rect> = local_rects
.into_iter()
.map(|rect_bounds: Rect| {
Rect::new(
rect_bounds.get_x() + ox,
rect_bounds.get_y() + oy,
rect_bounds.get_width(),
rect_bounds.get_height(),
)
})
.collect();
let mut sg_order: Vec<(usize, usize)> = (0..fc.get_subgraphs().len())
.map(|item_index: usize| (subgraph_depth(fc.get_subgraphs(), item_index), item_index))
.collect();
sg_order.sort_by_key(|&(delta_val, outer_index): &(usize, usize)| (delta_val, outer_index));
for (depth, sg_idx) in sg_order.into_iter() {
let sg: &MermaidSubgraph = &fc.get_subgraphs()[sg_idx];
let mut min_x: f32 = f32::INFINITY;
let mut min_y: f32 = f32::INFINITY;
let mut max_x: f32 = f32::NEG_INFINITY;
let mut max_y: f32 = f32::NEG_INFINITY;
for (ni, node) in fc.get_nodes().iter().enumerate() {
if subgraph_contains(fc.get_subgraphs(), node.get_subgraph(), sg_idx) {
let clip_bounds: Rect = rects[ni];
min_x = min_x.min(clip_bounds.get_x());
min_y = min_y.min(clip_bounds.get_y());
max_x = max_x.max(clip_bounds.right());
max_y = max_y.max(clip_bounds.bottom());
}
}
if min_x.is_finite() {
let nest_extra: f32 = if depth == 0 { 12.0 } else { 0.0 };
let pad_x: f32 = 16.0 + nest_extra;
let pad_top: f32 = 28.0 + nest_extra;
let pad_bot: f32 = 16.0 + nest_extra * 0.6;
let box_r: Rect = Rect::new(
min_x - pad_x,
min_y - pad_top,
(max_x - min_x) + pad_x * 2.0,
(max_y - min_y) + pad_top + pad_bot,
);
let tint_col: Color =
Color::hex(MERMAID_PIE_PALETTE[sg_idx % MERMAID_PIE_PALETTE.len()]);
display_list.push(DrawCommand::FillRoundedRect {
rect: box_r,
color: eva
.get_header_bg()
.with_alpha(if depth == 0 { 150 } else { 195 }),
radius: CornerRadius::all(10.0),
border: Border::new(1.3, tint_col.with_alpha(150)),
});
draw_centered_label(
display_list,
Rect::new(
box_r.get_x() + 10.0,
box_r.get_y() + 4.0,
box_r.get_width() - 20.0,
18.0,
),
sg.get_title(),
11.0,
FontWeight::Bold,
tint_col,
TextAlign::Left,
);
}
}
let mut id_map: HashMap<&str, usize> = HashMap::with_capacity(fc.get_nodes().len());
for (idx, node) in fc.get_nodes().iter().enumerate() {
let _: Option<usize> = id_map.insert(node.get_id().as_str(), idx);
}
let horiz: bool = matches!(
fc.get_direction(),
MermaidFlowDirection::LeftRight | MermaidFlowDirection::RightLeft
);
let edge_col: Color = eva.get_function();
let mut placed_pills: Vec<Rect> = Vec::with_capacity(fc.get_edges().len());
for edge in fc.get_edges().iter() {
let (Some(&tex_u), Some(&item_val)) = (
id_map.get(edge.get_from().as_str()),
id_map.get(edge.get_to().as_str()),
) else {
continue;
};
let ra: Rect = rects[tex_u];
let rb: Rect = rects[item_val];
let is_bidir: bool = tex_u != item_val
&& fc.get_edges().iter().any(|other: &MermaidFlowEdge| {
id_map.get(other.get_from().as_str()) == Some(&item_val)
&& id_map.get(other.get_to().as_str()) == Some(&tex_u)
});
let bidir_sign: f32 = if tex_u < item_val { -1.0 } else { 1.0 };
let (raw_p0, raw_p1): (Point, Point) = compute_rect_anchor_points(ra, rb, horiz);
let (p0, p1): (Point, Point) = if is_bidir {
if horiz {
let dy: f32 = bidir_sign * 14.0;
(
Point::new(raw_p0.get_x(), raw_p0.get_y() + dy),
Point::new(raw_p1.get_x(), raw_p1.get_y() + dy),
)
} else {
let dx: f32 = bidir_sign * 24.0;
(
Point::new(raw_p0.get_x() + dx, raw_p0.get_y()),
Point::new(raw_p1.get_x() + dx, raw_p1.get_y()),
)
}
} else {
(raw_p0, raw_p1)
};
draw_styled_edge(display_list, p0, p1, edge.get_style(), edge_col);
if !edge.get_label().is_empty() {
let mx: f32 = (p0.get_x() + p1.get_x()) * 0.5;
let my: f32 = (p0.get_y() + p1.get_y()) * 0.5;
let lbl_w: f32 = ((edge.get_label().chars().count() as f32) * 6.8 + 14.0).max(34.0);
let (pill_x, pill_y): (f32, f32) = if is_bidir {
if horiz {
let py: f32 = if bidir_sign < 0.0 {
my - 24.0
} else {
my + 4.0
};
(mx - lbl_w * 0.5, py)
} else {
let px: f32 = if bidir_sign < 0.0 {
mx - lbl_w - 8.0
} else {
mx + 8.0
};
(px, my - 10.0)
}
} else {
(mx - lbl_w * 0.5, my - 10.0)
};
let base_pill: Rect = Rect::new(pill_x, pill_y, lbl_w, 20.0);
let pill: Rect = resolve_edge_pill_rect(p0, p1, base_pill, &placed_pills, &rects);
placed_pills.push(pill);
display_list.push(DrawCommand::FillRoundedRect {
rect: pill,
color: eva.get_header_bg(),
radius: CornerRadius::all(5.0),
border: Border::new(1.0, eva.get_border()),
});
draw_centered_label(
display_list,
pill,
edge.get_label(),
10.5,
FontWeight::SemiBold,
eva.get_foreground(),
TextAlign::Center,
);
}
}
for (idx, node) in fc.get_nodes().iter().enumerate() {
draw_flowchart_node(display_list, node, rects[idx], palette, eva);
}
}
fn draw_flowchart_node(
display_list: &mut DisplayList,
node: &MermaidFlowNode,
rect_bounds: Rect,
palette: ThemePalette,
eva: CodeThemePalette,
) {
let custom_fill: Option<Color> = node.try_get_fill().as_deref().and_then(parse_mermaid_color);
let custom_stroke: Option<Color> = node
.try_get_stroke()
.as_deref()
.and_then(parse_mermaid_color);
let custom_fg: Option<Color> = node
.try_get_text_color()
.as_deref()
.and_then(parse_mermaid_color);
let fill: Color = custom_fill.unwrap_or_else(|| palette.get_card());
let fg: Color = custom_fg.unwrap_or_else(|| palette.get_foreground());
let default_stroke: Color = eva.get_keyword();
let cx: f32 = rect_bounds.get_x() + rect_bounds.get_width() * 0.5;
let cy: f32 = rect_bounds.get_y() + rect_bounds.get_height() * 0.5;
match node.get_shape() {
MermaidNodeShape::StateStart => {
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: 9.0,
color: custom_stroke.unwrap_or(default_stroke),
});
}
MermaidNodeShape::StateEnd => {
let color_value: Color = custom_stroke.unwrap_or(default_stroke);
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: 11.0,
color: color_value,
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: 7.5,
color: eva.get_background(),
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: 4.5,
color: color_value,
});
}
MermaidNodeShape::ForkJoin => {
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: custom_fill.unwrap_or_else(|| palette.get_foreground()),
radius: CornerRadius::all(3.0),
border: Border::default(),
});
}
MermaidNodeShape::Note => {
let note_stroke: Color = custom_stroke.unwrap_or_else(|| palette.get_warning());
let note_fill: Color =
custom_fill.unwrap_or_else(|| palette.get_warning().with_alpha(34));
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: note_fill,
radius: CornerRadius::all(6.0),
border: Border::new(1.3, note_stroke),
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.0,
FontWeight::Medium,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Circle => {
let rad: f32 = rect_bounds.get_width().min(rect_bounds.get_height()) * 0.5;
let tint_color: Color = custom_stroke.unwrap_or_else(|| eva.get_operator());
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: rad,
color: tint_color,
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: (rad - 1.8).max(2.0),
color: fill,
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::DoubleCircle => {
let rad: f32 = rect_bounds.get_width().min(rect_bounds.get_height()) * 0.5;
let sampled_color: Color = custom_stroke.unwrap_or_else(|| eva.get_operator());
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: rad,
color: sampled_color,
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: (rad - 1.8).max(2.0),
color: eva.get_background(),
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: (rad - 4.5).max(2.0),
color: sampled_color,
});
display_list.push(DrawCommand::Circle {
center: Point::new(cx, cy),
radius: (rad - 6.3).max(2.0),
color: fill,
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.0,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Diamond => {
let pts: [Point; 4] = [
Point::new(cx, rect_bounds.get_y()),
Point::new(rect_bounds.right(), cy),
Point::new(cx, rect_bounds.bottom()),
Point::new(rect_bounds.get_x(), cy),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_control()),
1.8,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Hexagon => {
let inset: f32 = 14.0;
let pts: [Point; 6] = [
Point::new(rect_bounds.get_x() + inset, rect_bounds.get_y()),
Point::new(rect_bounds.right() - inset, rect_bounds.get_y()),
Point::new(rect_bounds.right(), cy),
Point::new(rect_bounds.right() - inset, rect_bounds.bottom()),
Point::new(rect_bounds.get_x() + inset, rect_bounds.bottom()),
Point::new(rect_bounds.get_x(), cy),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_control()),
1.7,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Parallelogram => {
let slant: f32 = 12.0;
let pts: [Point; 4] = [
Point::new(rect_bounds.get_x() + slant, rect_bounds.get_y()),
Point::new(rect_bounds.right(), rect_bounds.get_y()),
Point::new(rect_bounds.right() - slant, rect_bounds.bottom()),
Point::new(rect_bounds.get_x(), rect_bounds.bottom()),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_function()),
1.6,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::ParallelogramAlt => {
let slant: f32 = 12.0;
let pts: [Point; 4] = [
Point::new(rect_bounds.get_x(), rect_bounds.get_y()),
Point::new(rect_bounds.right() - slant, rect_bounds.get_y()),
Point::new(rect_bounds.right(), rect_bounds.bottom()),
Point::new(rect_bounds.get_x() + slant, rect_bounds.bottom()),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_function()),
1.6,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Trapezoid => {
let slant: f32 = 12.0;
let pts: [Point; 4] = [
Point::new(rect_bounds.get_x() + slant, rect_bounds.get_y()),
Point::new(rect_bounds.right() - slant, rect_bounds.get_y()),
Point::new(rect_bounds.right(), rect_bounds.bottom()),
Point::new(rect_bounds.get_x(), rect_bounds.bottom()),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_operator()),
1.6,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::TrapezoidAlt => {
let slant: f32 = 12.0;
let pts: [Point; 4] = [
Point::new(rect_bounds.get_x(), rect_bounds.get_y()),
Point::new(rect_bounds.right(), rect_bounds.get_y()),
Point::new(rect_bounds.right() - slant, rect_bounds.bottom()),
Point::new(rect_bounds.get_x() + slant, rect_bounds.bottom()),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_operator()),
1.6,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Asymmetric => {
let notch: f32 = 12.0;
let pts: [Point; 5] = [
Point::new(rect_bounds.get_x(), rect_bounds.get_y()),
Point::new(rect_bounds.right() - notch, rect_bounds.get_y()),
Point::new(rect_bounds.right(), cy),
Point::new(rect_bounds.right() - notch, rect_bounds.bottom()),
Point::new(rect_bounds.get_x(), rect_bounds.bottom()),
];
draw_polygon(
display_list,
&pts,
fill,
custom_stroke.unwrap_or_else(|| eva.get_property()),
1.6,
);
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Subroutine => {
let node_style: Color = custom_stroke.unwrap_or_else(|| eva.get_link());
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: fill,
radius: CornerRadius::all(4.0),
border: Border::new(1.6, node_style),
});
display_list.push(DrawCommand::Line {
from: Point::new(rect_bounds.get_x() + 9.0, rect_bounds.get_y()),
to: Point::new(rect_bounds.get_x() + 9.0, rect_bounds.bottom()),
color: node_style,
width: 1.4,
});
display_list.push(DrawCommand::Line {
from: Point::new(rect_bounds.right() - 9.0, rect_bounds.get_y()),
to: Point::new(rect_bounds.right() - 9.0, rect_bounds.bottom()),
color: node_style,
width: 1.4,
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Cylinder => {
let active_style: Color = custom_stroke.unwrap_or_else(|| eva.get_diff_add());
let cap_h: f32 = 11.0;
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: fill,
radius: CornerRadius::all(cap_h),
border: Border::new(1.6, active_style),
});
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
rect_bounds.get_x(),
rect_bounds.get_y(),
rect_bounds.get_width(),
cap_h * 1.4,
),
color: eva.get_header_bg(),
radius: CornerRadius::all(cap_h),
border: Border::new(1.4, active_style),
});
draw_centered_label(
display_list,
Rect::new(
rect_bounds.get_x(),
rect_bounds.get_y() + cap_h * 0.9,
rect_bounds.get_width(),
rect_bounds.get_height() - cap_h,
),
node.get_label(),
11.5,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Stadium => {
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: fill,
radius: CornerRadius::all(RADIUS_PILL),
border: Border::new(1.6, custom_stroke.unwrap_or_else(|| eva.get_diff_add())),
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
12.0,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Rounded => {
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: fill,
radius: CornerRadius::all(12.0),
border: Border::new(1.6, custom_stroke.unwrap_or(default_stroke)),
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
12.0,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
MermaidNodeShape::Box => {
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: fill,
radius: CornerRadius::all(6.0),
border: Border::new(1.6, custom_stroke.unwrap_or_else(|| eva.get_link())),
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
12.0,
FontWeight::SemiBold,
fg,
TextAlign::Center,
);
}
}
}
fn draw_styled_edge(
display_list: &mut DisplayList,
from: Point,
to: Point,
style: MermaidEdgeStyle,
color: Color,
) {
let stroke_w: f32 = match style {
MermaidEdgeStyle::Thick | MermaidEdgeStyle::ThickPlain | MermaidEdgeStyle::ThickBidir => {
2.8
}
_ => 1.65,
};
let dashed: bool = matches!(
style,
MermaidEdgeStyle::Dashed
| MermaidEdgeStyle::DashedPlain
| MermaidEdgeStyle::DashedBidir
| MermaidEdgeStyle::DashedOpenArrow
| MermaidEdgeStyle::DashedAsyncArrow
| MermaidEdgeStyle::DashedCrossArrow
);
let end_arrow: bool = matches!(
style,
MermaidEdgeStyle::Solid
| MermaidEdgeStyle::Dashed
| MermaidEdgeStyle::Thick
| MermaidEdgeStyle::Bidir
| MermaidEdgeStyle::DashedBidir
| MermaidEdgeStyle::ThickBidir
);
let start_arrow: bool = matches!(
style,
MermaidEdgeStyle::Bidir | MermaidEdgeStyle::DashedBidir | MermaidEdgeStyle::ThickBidir
);
draw_vector_connector(display_list, from, to, color, stroke_w, dashed, end_arrow);
if start_arrow {
draw_arrowhead(display_list, to, from, color);
}
match style {
MermaidEdgeStyle::CircleEnd => {
display_list.push(DrawCommand::Circle {
center: to,
radius: 4.0,
color,
});
}
MermaidEdgeStyle::CircleBoth => {
display_list.push(DrawCommand::Circle {
center: from,
radius: 4.0,
color,
});
display_list.push(DrawCommand::Circle {
center: to,
radius: 4.0,
color,
});
}
MermaidEdgeStyle::CrossEnd
| MermaidEdgeStyle::CrossArrow
| MermaidEdgeStyle::DashedCrossArrow => {
draw_cross_marker(display_list, to, color, stroke_w);
}
MermaidEdgeStyle::CrossBoth => {
draw_cross_marker(display_list, from, color, stroke_w);
draw_cross_marker(display_list, to, color, stroke_w);
}
MermaidEdgeStyle::AsyncArrow | MermaidEdgeStyle::DashedAsyncArrow => {
draw_open_chevron(display_list, from, to, color, stroke_w);
}
_ => {}
}
}
fn draw_arrowhead(display_list: &mut DisplayList, tail: Point, tip: Point, color: Color) {
let dx: f32 = tip.get_x() - tail.get_x();
let dy: f32 = tip.get_y() - tail.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let base_x: f32 = tip.get_x() - ux * 8.5;
let base_y: f32 = tip.get_y() - uy * 8.5;
let left: Point = Point::new(base_x - uy * 4.6, base_y + ux * 4.6);
let right: Point = Point::new(base_x + uy * 4.6, base_y - ux * 4.6);
display_list.push(DrawCommand::Triangle {
p0: tip,
p1: left,
p2: right,
color,
});
}
fn draw_cross_marker(
display_list: &mut DisplayList,
point_coords: Point,
color: Color,
width: f32,
) {
let red_val: f32 = 4.5;
display_list.push(DrawCommand::Line {
from: Point::new(
point_coords.get_x() - red_val,
point_coords.get_y() - red_val,
),
to: Point::new(
point_coords.get_x() + red_val,
point_coords.get_y() + red_val,
),
color,
width,
});
display_list.push(DrawCommand::Line {
from: Point::new(
point_coords.get_x() - red_val,
point_coords.get_y() + red_val,
),
to: Point::new(
point_coords.get_x() + red_val,
point_coords.get_y() - red_val,
),
color,
width,
});
}
fn draw_open_chevron(
display_list: &mut DisplayList,
tail: Point,
tip: Point,
color: Color,
width: f32,
) {
let dx: f32 = tip.get_x() - tail.get_x();
let dy: f32 = tip.get_y() - tail.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let base_x: f32 = tip.get_x() - ux * 8.0;
let base_y: f32 = tip.get_y() - uy * 8.0;
let left: Point = Point::new(base_x - uy * 4.5, base_y + ux * 4.5);
let right: Point = Point::new(base_x + uy * 4.5, base_y - ux * 4.5);
display_list.push(DrawCommand::Line {
from: left,
to: tip,
color,
width,
});
display_list.push(DrawCommand::Line {
from: right,
to: tip,
color,
width,
});
}
fn draw_sequence(
seq: &MermaidSequence,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let count: usize = seq.get_participants().len();
if count == 0 {
return;
}
let col_step: f32 = ((bounds.get_width() - 48.0) / (count as f32)).max(140.0);
let total_w: f32 = col_step * (count as f32);
let start_x: f32 = bounds.get_x() + ((bounds.get_width() - total_w).max(0.0)) * 0.5;
let top_y: f32 = bounds.get_y() + 20.0;
let box_h: f32 = 36.0;
let box_w: f32 = (col_step - 24.0).clamp(84.0, 148.0);
let msg_start_y: f32 = top_y + box_h + 34.0;
let row_h: f32 = 46.0;
let bot_y: f32 = msg_start_y + (seq.get_messages().len().max(1) as f32) * row_h + 16.0;
let mut centers: Vec<f32> = Vec::with_capacity(count);
for (idx, (_, label)) in seq.get_participants().iter().enumerate() {
let cx: f32 = start_x + (idx as f32 + 0.5) * col_step;
centers.push(cx);
draw_dashed_line(
display_list,
Point::new(cx, top_y + box_h),
Point::new(cx, bot_y),
eva.get_border(),
1.3,
);
let is_actor: bool = seq.get_actor_flags().get(idx).copied().unwrap_or(false);
for by in [top_y, bot_y].into_iter() {
let pr: Rect = Rect::new(cx - box_w * 0.5, by, box_w, box_h);
if is_actor {
display_list.push(DrawCommand::Circle {
center: Point::new(cx, by + 7.0),
radius: 5.5,
color: eva.get_keyword(),
});
display_list.push(DrawCommand::Line {
from: Point::new(cx, by + 12.5),
to: Point::new(cx, by + 21.0),
color: eva.get_keyword(),
width: 1.5,
});
display_list.push(DrawCommand::Line {
from: Point::new(cx - 8.0, by + 15.5),
to: Point::new(cx + 8.0, by + 15.5),
color: eva.get_keyword(),
width: 1.5,
});
draw_centered_label(
display_list,
Rect::new(pr.get_x(), by + 21.0, pr.get_width(), 16.0),
label,
11.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
} else {
display_list.push(DrawCommand::FillRoundedRect {
rect: pr,
color: palette.get_card(),
radius: CornerRadius::all(7.0),
border: Border::new(1.5, eva.get_link()),
});
draw_centered_label(
display_list,
pr,
label,
12.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
}
}
}
for blk in seq.get_blocks().iter() {
let inset: f32 = (blk.get_depth() as f32) * 8.0;
let bx: f32 = start_x + 8.0 + inset;
let border_width: f32 = (total_w - 16.0 - inset * 2.0).max(120.0);
let by: f32 = msg_start_y + (blk.get_start_row() as f32) * row_h - 24.0;
let bh: f32 =
(((blk.get_end_row() - blk.get_start_row() + 1) as f32) * row_h + 24.0).max(48.0);
let blk_col: Color = match blk.get_kind() {
MermaidSeqBlockKind::Loop => eva.get_function(),
MermaidSeqBlockKind::Alt => eva.get_keyword(),
MermaidSeqBlockKind::Opt => eva.get_operator(),
MermaidSeqBlockKind::Par => eva.get_diff_add(),
MermaidSeqBlockKind::Critical => eva.get_diff_del(),
MermaidSeqBlockKind::Break => palette.get_warning(),
MermaidSeqBlockKind::Rect => eva.get_control(),
};
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(bx, by, border_width, bh),
color: blk_col.with_alpha(18),
radius: CornerRadius::all(6.0),
border: Border::new(1.2, blk_col.with_alpha(160)),
});
let kind_str: &str = match blk.get_kind() {
MermaidSeqBlockKind::Loop => MERMAID_BLK_LOOP,
MermaidSeqBlockKind::Alt => MERMAID_BLK_ALT,
MermaidSeqBlockKind::Opt => MERMAID_BLK_OPT,
MermaidSeqBlockKind::Par => MERMAID_BLK_PAR,
MermaidSeqBlockKind::Critical => MERMAID_BLK_CRITICAL,
MermaidSeqBlockKind::Break => MERMAID_BLK_BREAK,
MermaidSeqBlockKind::Rect => MERMAID_BLK_RECT,
};
let tab_w: f32 = ((kind_str.len() as f32) * 7.2 + 16.0).max(46.0);
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(bx, by, tab_w, 18.0),
color: blk_col.with_alpha(200),
radius: CornerRadius::new(6.0, 0.0, 6.0, 0.0),
border: Border::default(),
});
draw_centered_label(
display_list,
Rect::new(bx, by, tab_w, 18.0),
kind_str,
10.0,
FontWeight::Bold,
palette.get_primary_foreground(),
TextAlign::Center,
);
if !blk.get_label().is_empty() {
draw_centered_label(
display_list,
Rect::new(bx + tab_w + 8.0, by, border_width - tab_w - 16.0, 18.0),
blk.get_label(),
10.5,
FontWeight::SemiBold,
eva.get_foreground(),
TextAlign::Left,
);
}
for div in blk.get_dividers().iter() {
let dy: f32 = msg_start_y + (div.get_row_idx() as f32) * row_h - 14.0;
draw_dashed_line(
display_list,
Point::new(bx, dy),
Point::new(bx + border_width, dy),
blk_col.with_alpha(160),
1.1,
);
if !div.get_label().is_empty() {
draw_centered_label(
display_list,
Rect::new(bx + 10.0, dy + 2.0, border_width - 20.0, 16.0),
div.get_label(),
10.0,
FontWeight::SemiBold,
blk_col,
TextAlign::Left,
);
}
}
}
for act in seq.get_activations().iter() {
if let Some(&cx) = centers.get(act.get_participant_idx()) {
let ay: f32 = msg_start_y + (act.get_start_row() as f32) * row_h - 6.0;
let ah: f32 =
(((act.get_end_row() - act.get_start_row() + 1) as f32) * row_h - 14.0).max(20.0);
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(cx - 5.0, ay, 10.0, ah),
color: eva.get_function().with_alpha(64),
radius: CornerRadius::all(3.0),
border: Border::new(1.2, eva.get_function()),
});
}
}
let mut seq_num: usize = 0;
for (m_idx, msg) in seq.get_messages().iter().enumerate() {
let pos_y: f32 = msg_start_y + (m_idx as f32) * row_h;
let x0: f32 = centers.get(msg.get_from_idx()).copied().unwrap_or(start_x);
let x1: f32 = centers.get(msg.get_to_idx()).copied().unwrap_or(x0);
if msg.get_is_note() {
let note_w: f32 =
((msg.get_text().chars().count() as f32) * 6.8 + 26.0).clamp(112.0, 220.0);
let nr: Rect = match msg.get_note_placement() {
MermaidSeqNotePlacement::LeftOf => {
Rect::new(x0 - note_w - 10.0, pos_y - 14.0, note_w, 28.0)
}
MermaidSeqNotePlacement::RightOf => {
Rect::new(x0 + 10.0, pos_y - 14.0, note_w, 28.0)
}
MermaidSeqNotePlacement::Over => {
let left_x: f32 = x0.min(x1) - 54.0;
let right_x: f32 = x0.max(x1) + 54.0;
Rect::new(left_x, pos_y - 14.0, (right_x - left_x).max(note_w), 28.0)
}
};
display_list.push(DrawCommand::FillRoundedRect {
rect: nr,
color: palette.get_warning().with_alpha(38),
radius: CornerRadius::all(6.0),
border: Border::new(1.2, palette.get_warning()),
});
draw_centered_label(
display_list,
nr,
msg.get_text(),
11.0,
FontWeight::Medium,
palette.get_foreground(),
TextAlign::Center,
);
continue;
}
seq_num += 1;
let display_text: String = if seq.get_autonumber() {
format!("{seq_num}. {}", msg.get_text())
} else {
msg.get_text().clone()
};
let dashed: bool = matches!(
msg.get_style(),
MermaidEdgeStyle::Dashed
| MermaidEdgeStyle::DashedOpenArrow
| MermaidEdgeStyle::DashedAsyncArrow
| MermaidEdgeStyle::DashedCrossArrow
);
let col: Color = if dashed {
eva.get_operator()
} else {
eva.get_function()
};
if (x1 - x0).abs() < 1.0 {
let loop_w: f32 = 42.0;
let loop_h: f32 = 22.0;
draw_vector_connector(
display_list,
Point::new(x0, pos_y),
Point::new(x0 + loop_w, pos_y),
col,
1.6,
dashed,
false,
);
draw_vector_connector(
display_list,
Point::new(x0 + loop_w, pos_y),
Point::new(x0 + loop_w, pos_y + loop_h),
col,
1.6,
dashed,
false,
);
draw_styled_edge(
display_list,
Point::new(x0 + loop_w, pos_y + loop_h),
Point::new(x0, pos_y + loop_h),
msg.get_style(),
col,
);
draw_centered_label(
display_list,
Rect::new(x0 + 6.0, pos_y - 18.0, 150.0, 16.0),
&display_text,
11.0,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Left,
);
} else {
draw_styled_edge(
display_list,
Point::new(x0, pos_y + 6.0),
Point::new(x1, pos_y + 6.0),
msg.get_style(),
col,
);
let min_x: f32 = x0.min(x1);
let span: f32 = (x1 - x0).abs().max(84.0);
draw_centered_label(
display_list,
Rect::new(min_x, pos_y - 14.0, span, 18.0),
&display_text,
11.5,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Center,
);
}
}
}
fn draw_class_diagram(
cls: &MermaidClassDiagram,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let count: usize = cls.get_classes().len();
if count == 0 {
return;
}
let cols: usize = count.clamp(1, 3);
let box_w: f32 = 210.0;
let gap_x: f32 = 38.0;
let gap_y: f32 = 46.0;
let max_m: usize = cls
.get_classes()
.iter()
.map(|char_item: &MermaidClassBox| {
char_item.get_members().len() + usize::from(!char_item.get_stereotype().is_empty())
})
.max()
.unwrap_or(1);
let box_h: f32 = 44.0 + (max_m as f32) * 18.0;
let grid_w: f32 = (cols as f32) * box_w + ((cols.saturating_sub(1)) as f32) * gap_x;
let start_x: f32 = bounds.get_x() + ((bounds.get_width() - grid_w).max(0.0)) * 0.5;
let start_y: f32 = bounds.get_y() + 24.0;
let mut map: HashMap<&str, Rect> = HashMap::with_capacity(count);
let mut rects: Vec<Rect> = Vec::with_capacity(count);
for (idx, item) in cls.get_classes().iter().enumerate() {
let col: usize = idx % cols;
let row: usize = idx / cols;
let rx: f32 = start_x + (col as f32) * (box_w + gap_x);
let ry: f32 = start_y + (row as f32) * (box_h + gap_y);
let rect_bounds: Rect = Rect::new(rx, ry, box_w, box_h);
let _: Option<Rect> = map.insert(item.get_name().as_str(), rect_bounds);
rects.push(rect_bounds);
}
for rel in cls.get_relations().iter() {
if let (Some(&ra), Some(&rb)) = (
map.get(rel.get_from().as_str()),
map.get(rel.get_to().as_str()),
) {
let horiz: bool = (ra.get_y() - rb.get_y()).abs() < 8.0;
let (p0, p1): (Point, Point) = compute_rect_anchor_points(ra, rb, horiz);
let dashed: bool = matches!(
rel.get_style(),
MermaidEdgeStyle::Dashed | MermaidEdgeStyle::DashedPlain
);
let show_arrow: bool = matches!(
rel.get_rel_kind(),
MermaidClassRelKind::Association | MermaidClassRelKind::Dependency
);
draw_vector_connector(
display_list,
p0,
p1,
eva.get_function(),
1.6,
dashed,
show_arrow,
);
match rel.get_rel_kind() {
MermaidClassRelKind::Inheritance | MermaidClassRelKind::Realization => {
draw_hollow_triangle(
display_list,
p1,
p0,
eva.get_background(),
eva.get_function(),
);
}
MermaidClassRelKind::Composition => {
draw_uml_diamond(display_list, p0, p1, eva.get_function(), eva.get_function());
}
MermaidClassRelKind::Aggregation => {
draw_uml_diamond(
display_list,
p0,
p1,
eva.get_background(),
eva.get_function(),
);
}
_ => {}
}
if !rel.get_label().is_empty() {
let mx: f32 = (p0.get_x() + p1.get_x()) * 0.5;
let my: f32 = (p0.get_y() + p1.get_y()) * 0.5;
draw_centered_label(
display_list,
Rect::new(mx - 48.0, my - 10.0, 96.0, 18.0),
rel.get_label(),
10.5,
FontWeight::SemiBold,
eva.get_foreground(),
TextAlign::Center,
);
}
}
}
for (idx, item) in cls.get_classes().iter().enumerate() {
let clip_bounds: Rect = rects[idx];
let has_stereo: bool = !item.get_stereotype().is_empty();
let hdr_h: f32 = if has_stereo { 42.0 } else { 28.0 };
display_list.push(DrawCommand::FillRoundedRect {
rect: clip_bounds,
color: palette.get_card(),
radius: CornerRadius::all(8.0),
border: Border::new(1.5, eva.get_keyword()),
});
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
clip_bounds.get_x(),
clip_bounds.get_y(),
clip_bounds.get_width(),
hdr_h,
),
color: eva.get_keyword().with_alpha(32),
radius: CornerRadius::new(8.0, 8.0, 0.0, 0.0),
border: Border::default(),
});
display_list.push(DrawCommand::Line {
from: Point::new(clip_bounds.get_x(), clip_bounds.get_y() + hdr_h),
to: Point::new(clip_bounds.right(), clip_bounds.get_y() + hdr_h),
color: eva.get_border(),
width: 1.0,
});
if has_stereo {
draw_centered_label(
display_list,
Rect::new(
clip_bounds.get_x(),
clip_bounds.get_y() + 3.0,
clip_bounds.get_width(),
15.0,
),
item.get_stereotype(),
10.0,
FontWeight::Medium,
eva.get_keyword(),
TextAlign::Center,
);
draw_centered_label(
display_list,
Rect::new(
clip_bounds.get_x(),
clip_bounds.get_y() + 18.0,
clip_bounds.get_width(),
20.0,
),
item.get_name(),
12.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
} else {
draw_centered_label(
display_list,
Rect::new(
clip_bounds.get_x(),
clip_bounds.get_y(),
clip_bounds.get_width(),
hdr_h,
),
item.get_name(),
12.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
}
for (mi, mem) in item.get_members().iter().enumerate() {
let my: f32 = clip_bounds.get_y() + hdr_h + 6.0 + (mi as f32) * 18.0;
draw_centered_label(
display_list,
Rect::new(
clip_bounds.get_x() + 10.0,
my,
clip_bounds.get_width() - 20.0,
16.0,
),
mem,
11.0,
FontWeight::Normal,
eva.get_foreground(),
TextAlign::Left,
);
}
}
}
fn draw_hollow_triangle(
display_list: &mut DisplayList,
tail: Point,
tip: Point,
fill: Color,
stroke: Color,
) {
let dx: f32 = tip.get_x() - tail.get_x();
let dy: f32 = tip.get_y() - tail.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let bx: f32 = tip.get_x() - ux * 10.0;
let by: f32 = tip.get_y() - uy * 10.0;
let pts: [Point; 3] = [
tip,
Point::new(bx - uy * 5.5, by + ux * 5.5),
Point::new(bx + uy * 5.5, by - ux * 5.5),
];
draw_polygon(display_list, &pts, fill, stroke, 1.5);
}
fn draw_uml_diamond(
display_list: &mut DisplayList,
anchor: Point,
toward: Point,
fill: Color,
stroke: Color,
) {
let dx: f32 = toward.get_x() - anchor.get_x();
let dy: f32 = toward.get_y() - anchor.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let mid_x: f32 = anchor.get_x() + ux * 6.0;
let mid_y: f32 = anchor.get_y() + uy * 6.0;
let far: Point = Point::new(anchor.get_x() + ux * 12.0, anchor.get_y() + uy * 12.0);
let pts: [Point; 4] = [
anchor,
Point::new(mid_x - uy * 4.5, mid_y + ux * 4.5),
far,
Point::new(mid_x + uy * 4.5, mid_y - ux * 4.5),
];
draw_polygon(display_list, &pts, fill, stroke, 1.5);
}
fn draw_er_diagram(
er: &MermaidErDiagram,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let count: usize = er.get_entities().len();
if count == 0 {
return;
}
let cols: usize = count.clamp(1, 3);
let box_w: f32 = 212.0;
let gap_x: f32 = 52.0;
let gap_y: f32 = 46.0;
let max_a: usize = er
.get_entities()
.iter()
.map(|event_ref: &MermaidErEntity| event_ref.get_attributes().len())
.max()
.unwrap_or(1);
let box_h: f32 = 44.0 + (max_a as f32) * 18.0;
let grid_w: f32 = (cols as f32) * box_w + ((cols.saturating_sub(1)) as f32) * gap_x;
let start_x: f32 = bounds.get_x() + ((bounds.get_width() - grid_w).max(0.0)) * 0.5;
let start_y: f32 = bounds.get_y() + 24.0;
let mut map: HashMap<&str, Rect> = HashMap::with_capacity(count);
let mut rects: Vec<Rect> = Vec::with_capacity(count);
for (idx, ent) in er.get_entities().iter().enumerate() {
let col: usize = idx % cols;
let row: usize = idx / cols;
let rect_bounds: Rect = Rect::new(
start_x + (col as f32) * (box_w + gap_x),
start_y + (row as f32) * (box_h + gap_y),
box_w,
box_h,
);
let _: Option<Rect> = map.insert(ent.get_name().as_str(), rect_bounds);
rects.push(rect_bounds);
}
for rel in er.get_relations().iter() {
if let (Some(&ra), Some(&rb)) = (
map.get(rel.get_left().as_str()),
map.get(rel.get_right().as_str()),
) {
let horiz: bool = (ra.get_y() - rb.get_y()).abs() < 8.0;
let (p0, p1): (Point, Point) = compute_rect_anchor_points(ra, rb, horiz);
draw_vector_connector(
display_list,
p0,
p1,
eva.get_operator(),
1.6,
rel.get_dashed(),
false,
);
draw_er_crows_foot(
display_list,
p0,
p1,
rel.get_left_card(),
eva.get_operator(),
eva.get_background(),
);
draw_er_crows_foot(
display_list,
p1,
p0,
rel.get_right_card(),
eva.get_operator(),
eva.get_background(),
);
let caption: String = if rel.get_label().is_empty() {
format!("{}..{}", rel.get_left_card(), rel.get_right_card())
} else {
rel.get_label().clone()
};
let mx: f32 = (p0.get_x() + p1.get_x()) * 0.5;
let my: f32 = (p0.get_y() + p1.get_y()) * 0.5;
draw_centered_label(
display_list,
Rect::new(mx - 54.0, my - 12.0, 108.0, 18.0),
&caption,
10.5,
FontWeight::SemiBold,
eva.get_foreground(),
TextAlign::Center,
);
}
}
for (idx, ent) in er.get_entities().iter().enumerate() {
let clip_bounds: Rect = rects[idx];
display_list.push(DrawCommand::FillRoundedRect {
rect: clip_bounds,
color: palette.get_card(),
radius: CornerRadius::all(8.0),
border: Border::new(1.5, eva.get_operator()),
});
let hdr_r: Rect = Rect::new(
clip_bounds.get_x(),
clip_bounds.get_y(),
clip_bounds.get_width(),
28.0,
);
display_list.push(DrawCommand::FillRoundedRect {
rect: hdr_r,
color: eva.get_operator().with_alpha(32),
radius: CornerRadius::new(8.0, 8.0, 0.0, 0.0),
border: Border::default(),
});
draw_centered_label(
display_list,
hdr_r,
ent.get_name(),
12.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
for (align_items_mode, attr) in ent.get_attributes().iter().enumerate() {
let ay: f32 = clip_bounds.get_y() + 34.0 + (align_items_mode as f32) * 18.0;
let col: Color = if attr.contains(" PK") {
eva.get_keyword()
} else if attr.contains(" FK") {
eva.get_function()
} else {
eva.get_foreground()
};
draw_centered_label(
display_list,
Rect::new(
clip_bounds.get_x() + 10.0,
ay,
clip_bounds.get_width() - 20.0,
16.0,
),
attr,
11.0,
FontWeight::Normal,
col,
TextAlign::Left,
);
}
}
}
fn draw_er_crows_foot(
display_list: &mut DisplayList,
anchor: Point,
other: Point,
card: &str,
stroke: Color,
bg: Color,
) {
let dx: f32 = other.get_x() - anchor.get_x();
let dy: f32 = other.get_y() - anchor.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let px: f32 = -uy;
let py: f32 = ux;
let has_many: bool = card.contains('{') || card.contains('}');
let has_zero: bool = card.contains('o');
let bar_count: usize = card
.bytes()
.filter(|blue_val: &u8| *blue_val == b'|')
.count();
if has_many {
let base: Point = Point::new(anchor.get_x() + ux * 10.0, anchor.get_y() + uy * 10.0);
display_list.push(DrawCommand::Line {
from: base,
to: Point::new(anchor.get_x() + px * 6.0, anchor.get_y() + py * 6.0),
color: stroke,
width: 1.5,
});
display_list.push(DrawCommand::Line {
from: base,
to: Point::new(anchor.get_x() - px * 6.0, anchor.get_y() - py * 6.0),
color: stroke,
width: 1.5,
});
}
if bar_count >= 1 {
let d1: f32 = if has_many { 11.0 } else { 6.0 };
let c1: Point = Point::new(anchor.get_x() + ux * d1, anchor.get_y() + uy * d1);
display_list.push(DrawCommand::Line {
from: Point::new(c1.get_x() + px * 5.5, c1.get_y() + py * 5.5),
to: Point::new(c1.get_x() - px * 5.5, c1.get_y() - py * 5.5),
color: stroke,
width: 1.5,
});
}
if bar_count >= 2 {
let c2: Point = Point::new(anchor.get_x() + ux * 11.0, anchor.get_y() + uy * 11.0);
display_list.push(DrawCommand::Line {
from: Point::new(c2.get_x() + px * 5.5, c2.get_y() + py * 5.5),
to: Point::new(c2.get_x() - px * 5.5, c2.get_y() - py * 5.5),
color: stroke,
width: 1.5,
});
}
if has_zero {
let oc: Point = Point::new(anchor.get_x() + ux * 14.0, anchor.get_y() + uy * 14.0);
display_list.push(DrawCommand::Circle {
center: oc,
radius: 4.0,
color: stroke,
});
display_list.push(DrawCommand::Circle {
center: oc,
radius: 2.3,
color: bg,
});
}
}
fn draw_pie_chart(
pie: &MermaidPieChart,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let total: f32 = pie
.get_slices()
.iter()
.map(|source_val: &MermaidPieSlice| source_val.get_value())
.sum::<f32>()
.max(0.001);
let title_h: f32 = if pie.get_title().is_empty() {
14.0
} else {
36.0
};
if !pie.get_title().is_empty() {
draw_centered_label(
display_list,
Rect::new(
bounds.get_x() + 16.0,
bounds.get_y() + 10.0,
bounds.get_width() - 32.0,
22.0,
),
pie.get_title(),
13.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
}
let avail_h: f32 = (bounds.get_height() - title_h - 24.0).max(120.0);
let radius: f32 = (avail_h * 0.44).clamp(52.0, 92.0);
let cx: f32 = bounds.get_x() + radius + 44.0;
let cy: f32 = bounds.get_y() + title_h + avail_h * 0.5;
let center: Point = Point::new(cx, cy);
let mut start_angle: f32 = -FRAC_PI_2;
let legend_x: f32 = cx + radius + 38.0;
let legend_y0: f32 = bounds.get_y() + title_h + 18.0;
for (idx, slice) in pie.get_slices().iter().enumerate() {
let frac: f32 = slice.get_value() / total;
let sweep: f32 = frac * TAU;
let col: Color = Color::hex(MERMAID_PIE_PALETTE[idx % MERMAID_PIE_PALETTE.len()]);
let segs: usize = ((sweep / (PI / 24.0)).ceil() as usize).clamp(3, 64);
let step: f32 = sweep / (segs as f32);
for s_i in 0..segs {
let a0: f32 = start_angle + (s_i as f32) * step;
let a1: f32 = a0 + step;
let p1: Point = Point::new(cx + a0.cos() * radius, cy + a0.sin() * radius);
let p2: Point = Point::new(cx + a1.cos() * radius, cy + a1.sin() * radius);
display_list.push(DrawCommand::Triangle {
p0: center,
p1,
p2,
color: col,
});
}
start_angle += sweep;
let ly: f32 = legend_y0 + (idx as f32) * 26.0;
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(legend_x, ly + 3.0, 12.0, 12.0),
color: col,
radius: CornerRadius::all(3.0),
border: Border::default(),
});
let pct_txt: String = format!("{} ({:.1}%)", slice.get_label(), frac * 100.0);
draw_centered_label(
display_list,
Rect::new(
legend_x + 20.0,
ly,
(bounds.right() - legend_x - 28.0).max(120.0),
18.0,
),
&pct_txt,
12.0,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Left,
);
}
display_list.push(DrawCommand::Circle {
center,
radius: radius * 0.42,
color: eva.get_background(),
});
}
fn draw_gantt_chart(
gantt: &MermaidGanttChart,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let mut pos_y: f32 = bounds.get_y() + 14.0;
if !gantt.get_title().is_empty() {
draw_centered_label(
display_list,
Rect::new(
bounds.get_x() + 18.0,
pos_y,
bounds.get_width() - 36.0,
22.0,
),
gantt.get_title(),
13.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Left,
);
pos_y += 28.0;
}
let label_col_w: f32 = 172.0;
let track_x: f32 = bounds.get_x() + label_col_w + 16.0;
let track_w: f32 = (bounds.get_width() - label_col_w - 40.0).max(180.0);
let max_end: f32 = gantt
.get_tasks()
.iter()
.map(|blend_factor: &MermaidGanttTask| {
blend_factor.get_start_unit() + blend_factor.get_duration_unit()
})
.fold(1.0_f32, f32::max);
for tick in 0..=4 {
let tx: f32 = track_x + ((tick as f32) / 4.0) * track_w;
display_list.push(DrawCommand::Line {
from: Point::new(tx, pos_y),
to: Point::new(tx, bounds.bottom() - 16.0),
color: eva.get_border().with_alpha(120),
width: 1.0,
});
}
let mut last_sec: &str = "";
for task in gantt.get_tasks().iter() {
if task.get_section().as_str() != last_sec {
last_sec = task.get_section().as_str();
draw_centered_label(
display_list,
Rect::new(bounds.get_x() + 18.0, pos_y, label_col_w, 20.0),
last_sec,
11.5,
FontWeight::Bold,
eva.get_keyword(),
TextAlign::Left,
);
pos_y += 24.0;
}
draw_centered_label(
display_list,
Rect::new(bounds.get_x() + 24.0, pos_y + 2.0, label_col_w - 14.0, 22.0),
task.get_label(),
11.5,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Left,
);
let bx: f32 = track_x + (task.get_start_unit() / max_end) * track_w;
if task.get_status() == MermaidGanttStatus::Milestone {
let cy: f32 = pos_y + 13.0;
let pts: [Point; 4] = [
Point::new(bx, cy - 8.0),
Point::new(bx + 8.0, cy),
Point::new(bx, cy + 8.0),
Point::new(bx - 8.0, cy),
];
draw_polygon(
display_list,
&pts,
eva.get_control(),
eva.get_control(),
1.2,
);
} else {
let border_width: f32 = ((task.get_duration_unit() / max_end) * track_w).max(24.0);
let bar_col: Color = match task.get_status() {
MermaidGanttStatus::Done => eva.get_diff_add(),
MermaidGanttStatus::Active => eva.get_function(),
MermaidGanttStatus::Critical => eva.get_diff_del(),
MermaidGanttStatus::Normal | MermaidGanttStatus::Milestone => eva.get_operator(),
};
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(bx, pos_y + 3.0, border_width, 20.0),
color: bar_col,
radius: CornerRadius::all(5.0),
border: Border::default(),
});
}
pos_y += 32.0;
}
}
fn draw_timeline(
tl: &MermaidTimeline,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let count: usize = tl.get_events().len();
if count == 0 {
return;
}
let top_y: f32 = if tl.get_title().is_empty() {
bounds.get_y() + 20.0
} else {
draw_centered_label(
display_list,
Rect::new(
bounds.get_x() + 18.0,
bounds.get_y() + 12.0,
bounds.get_width() - 36.0,
22.0,
),
tl.get_title(),
13.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
bounds.get_y() + 46.0
};
let col_w: f32 = 166.0;
let gap: f32 = 18.0;
let total_w: f32 = (count as f32) * col_w + ((count.saturating_sub(1)) as f32) * gap;
let start_x: f32 = bounds.get_x() + ((bounds.get_width() - total_w).max(0.0)) * 0.5;
let spine_y: f32 = top_y + 18.0;
display_list.push(DrawCommand::Line {
from: Point::new(start_x + col_w * 0.5, spine_y),
to: Point::new(start_x + total_w - col_w * 0.5, spine_y),
color: eva.get_border(),
width: 2.0,
});
for (idx, ui_event) in tl.get_events().iter().enumerate() {
let col_col: Color = Color::hex(MERMAID_PIE_PALETTE[idx % MERMAID_PIE_PALETTE.len()]);
let pos_x: f32 = start_x + (idx as f32) * (col_w + gap);
let cx: f32 = pos_x + col_w * 0.5;
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(pos_x, top_y, col_w, 34.0),
color: col_col.with_alpha(38),
radius: CornerRadius::all(8.0),
border: Border::new(1.5, col_col),
});
draw_centered_label(
display_list,
Rect::new(pos_x + 6.0, top_y, col_w - 12.0, 34.0),
ui_event.get_period(),
12.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
display_list.push(DrawCommand::Circle {
center: Point::new(cx, top_y + 42.0),
radius: 4.5,
color: col_col,
});
for (ii, item) in ui_event.get_items().iter().enumerate() {
let iy: f32 = top_y + 54.0 + (ii as f32) * 32.0;
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(pos_x, iy, col_w, 26.0),
color: palette.get_card(),
radius: CornerRadius::all(6.0),
border: Border::new(1.0, eva.get_border()),
});
draw_centered_label(
display_list,
Rect::new(pos_x + 6.0, iy, col_w - 12.0, 26.0),
item,
11.0,
FontWeight::Normal,
eva.get_foreground(),
TextAlign::Center,
);
}
}
}
fn draw_mindmap(
mm: &MermaidMindmap,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let count: usize = mm.get_nodes().len();
if count == 0 {
return;
}
let mut rects: Vec<Rect> = Vec::with_capacity(count);
let mut parent_stack: Vec<(usize, usize)> = Vec::new();
let mut edges: Vec<(usize, usize)> = Vec::new();
let base_x: f32 = bounds.get_x() + 26.0;
let base_y: f32 = bounds.get_y() + 24.0;
for (idx, node) in mm.get_nodes().iter().enumerate() {
let delta_val: usize = node.get_depth();
while let Some(&(pd, _)) = parent_stack.last() {
if pd >= delta_val {
let _: Option<(usize, usize)> = parent_stack.pop();
} else {
break;
}
}
if let Some(&(_, pidx)) = parent_stack.last() {
edges.push((pidx, idx));
}
parent_stack.push((delta_val, idx));
let nw: f32 = ((node.get_label().chars().count() as f32) * 7.6 + 32.0).clamp(96.0, 170.0);
let rx: f32 = base_x + (delta_val as f32) * 184.0;
let ry: f32 = base_y + (idx as f32) * 38.0;
rects.push(Rect::new(rx, ry, nw, 30.0));
}
for &(tex_u, item_val) in edges.iter() {
let ra: Rect = rects[tex_u];
let rb: Rect = rects[item_val];
let p0: Point = Point::new(ra.right(), ra.get_y() + ra.get_height() * 0.5);
let p1: Point = Point::new(rb.get_x(), rb.get_y() + rb.get_height() * 0.5);
let mid_x: f32 = (p0.get_x() + p1.get_x()) * 0.5;
let col: Color = Color::hex(MERMAID_PIE_PALETTE[item_val % MERMAID_PIE_PALETTE.len()]);
display_list.push(DrawCommand::Line {
from: p0,
to: Point::new(mid_x, p0.get_y()),
color: col,
width: 1.6,
});
display_list.push(DrawCommand::Line {
from: Point::new(mid_x, p0.get_y()),
to: Point::new(mid_x, p1.get_y()),
color: col,
width: 1.6,
});
display_list.push(DrawCommand::Line {
from: Point::new(mid_x, p1.get_y()),
to: p1,
color: col,
width: 1.6,
});
}
for (idx, node) in mm.get_nodes().iter().enumerate() {
let rect_bounds: Rect = rects[idx];
let accent: Color =
Color::hex(MERMAID_PIE_PALETTE[node.get_depth() % MERMAID_PIE_PALETTE.len()]);
let radius: f32 = if node.get_depth() == 0 {
rect_bounds.get_height() * 0.5
} else {
8.0
};
display_list.push(DrawCommand::FillRoundedRect {
rect: rect_bounds,
color: if node.get_depth() == 0 {
accent.with_alpha(44)
} else {
palette.get_card()
},
radius: CornerRadius::all(radius),
border: Border::new(1.5, accent),
});
draw_centered_label(
display_list,
rect_bounds,
node.get_label(),
if node.get_depth() == 0 { 12.5 } else { 11.5 },
if node.get_depth() == 0 {
FontWeight::Bold
} else {
FontWeight::SemiBold
},
palette.get_foreground(),
TextAlign::Center,
);
}
let _: CodeThemePalette = eva;
}
fn draw_xychart(
xy: &MermaidXyChart,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let plot_l: f32 = bounds.get_x() + 64.0;
let plot_r: f32 = bounds.right() - 28.0;
let plot_t: f32 = bounds.get_y()
+ if xy.get_title().is_empty() {
24.0
} else {
44.0
};
let plot_b: f32 = bounds.bottom() - 42.0;
let plot_w: f32 = (plot_r - plot_l).max(120.0);
let plot_h: f32 = (plot_b - plot_t).max(80.0);
if !xy.get_title().is_empty() {
draw_centered_label(
display_list,
Rect::new(
bounds.get_x() + 16.0,
bounds.get_y() + 10.0,
bounds.get_width() - 32.0,
22.0,
),
xy.get_title(),
13.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
}
let y_min: f32 = xy.get_y_min();
let y_span: f32 = (xy.get_y_max() - y_min).max(0.001);
for tick in 0..=4 {
let frac: f32 = (tick as f32) / 4.0;
let ty: f32 = plot_b - frac * plot_h;
display_list.push(DrawCommand::Line {
from: Point::new(plot_l, ty),
to: Point::new(plot_r, ty),
color: eva.get_border().with_alpha(120),
width: 1.0,
});
let val: f32 = y_min + frac * y_span;
draw_centered_label(
display_list,
Rect::new(bounds.get_x() + 6.0, ty - 8.0, 52.0, 16.0),
&format!("{val:.0}"),
10.5,
FontWeight::Normal,
eva.get_line_number(),
TextAlign::Right,
);
}
display_list.push(DrawCommand::Line {
from: Point::new(plot_l, plot_t),
to: Point::new(plot_l, plot_b),
color: eva.get_foreground(),
width: 1.4,
});
display_list.push(DrawCommand::Line {
from: Point::new(plot_l, plot_b),
to: Point::new(plot_r, plot_b),
color: eva.get_foreground(),
width: 1.4,
});
let x_cnt: usize = xy.get_x_labels().len().max(1);
let step_x: f32 = plot_w / (x_cnt as f32);
for (xi, label_text) in xy.get_x_labels().iter().enumerate() {
let cx: f32 = plot_l + (xi as f32 + 0.5) * step_x;
draw_centered_label(
display_list,
Rect::new(cx - step_x * 0.5, plot_b + 8.0, step_x, 18.0),
label_text,
10.5,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Center,
);
}
for (s_idx, ser) in xy.get_series().iter().enumerate() {
let col: Color = Color::hex(MERMAID_PIE_PALETTE[s_idx % MERMAID_PIE_PALETTE.len()]);
if ser.get_is_bar() {
let bar_w: f32 = (step_x * 0.54).clamp(12.0, 44.0);
for (vi, &item_val) in ser.get_values().iter().enumerate() {
let cx: f32 = plot_l + (vi as f32 + 0.5) * step_x;
let frac: f32 = ((item_val - y_min) / y_span).clamp(0.0, 1.0);
let bh: f32 = (frac * plot_h).max(2.0);
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(cx - bar_w * 0.5, plot_b - bh, bar_w, bh),
color: col.with_alpha(210),
radius: CornerRadius::new(4.0, 4.0, 0.0, 0.0),
border: Border::default(),
});
}
} else {
let mut prev_pt: Option<Point> = None;
for (vi, &tex_v) in ser.get_values().iter().enumerate() {
let cx: f32 = plot_l + (vi as f32 + 0.5) * step_x;
let frac: f32 = ((tex_v - y_min) / y_span).clamp(0.0, 1.0);
let point_coords: Point = Point::new(cx, plot_b - frac * plot_h);
if let Some(prev) = prev_pt {
display_list.push(DrawCommand::Line {
from: prev,
to: point_coords,
color: col,
width: 2.2,
});
}
display_list.push(DrawCommand::Circle {
center: point_coords,
radius: 4.0,
color: col,
});
prev_pt = Some(point_coords);
}
}
}
}
fn draw_gitgraph(
git: &MermaidGitGraph,
bounds: Rect,
display_list: &mut DisplayList,
tokens: ThemeTokens,
eva: CodeThemePalette,
) {
let palette: ThemePalette = tokens.get_palette();
let b_cnt: usize = git.get_branches().len();
if b_cnt == 0 {
return;
}
let lane_h: f32 = 48.0;
let label_w: f32 = 96.0;
let start_x: f32 = bounds.get_x() + label_w + 26.0;
let start_y: f32 = bounds.get_y() + 34.0;
let step_x: f32 = 74.0;
let track_end_x: f32 = start_x + (git.get_commits().len().max(1) as f32) * step_x;
for (bi, bname) in git.get_branches().iter().enumerate() {
let ly: f32 = start_y + (bi as f32) * lane_h;
let col: Color = Color::hex(MERMAID_PIE_PALETTE[bi % MERMAID_PIE_PALETTE.len()]);
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(bounds.get_x() + 14.0, ly - 11.0, label_w - 8.0, 22.0),
color: col.with_alpha(36),
radius: CornerRadius::all(6.0),
border: Border::new(1.2, col),
});
draw_centered_label(
display_list,
Rect::new(bounds.get_x() + 18.0, ly - 11.0, label_w - 16.0, 22.0),
bname,
11.0,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
display_list.push(DrawCommand::Line {
from: Point::new(start_x - 12.0, ly),
to: Point::new(track_end_x, ly),
color: col.with_alpha(120),
width: 2.0,
});
}
let mut positions: Vec<Point> = Vec::with_capacity(git.get_commits().len());
for (ci, commit) in git.get_commits().iter().enumerate() {
let cx: f32 = start_x + (ci as f32) * step_x;
let cy: f32 = start_y + (commit.get_lane() as f32) * lane_h;
let point_coords: Point = Point::new(cx, cy);
positions.push(point_coords);
let col: Color =
Color::hex(MERMAID_PIE_PALETTE[commit.get_lane() % MERMAID_PIE_PALETTE.len()]);
if let Some(pidx) = commit.get_parent_idx()
&& let Some(&prev_pt) = positions.get(pidx)
{
display_list.push(DrawCommand::Line {
from: prev_pt,
to: point_coords,
color: col,
width: 2.4,
});
}
if let Some(src_lane) = commit.get_merge_from_lane()
&& let Some(src_pt) = positions
.iter()
.enumerate()
.rev()
.find(|&(item_index, _): &(usize, &Point)| {
item_index < ci && git.get_commits()[item_index].get_lane() == src_lane
})
.map(|(_, &pos): (usize, &Point)| pos)
{
let merge_col: Color =
Color::hex(MERMAID_PIE_PALETTE[src_lane % MERMAID_PIE_PALETTE.len()]);
draw_dashed_line(display_list, src_pt, point_coords, merge_col, 2.0);
}
}
for (ci, commit) in git.get_commits().iter().enumerate() {
let cursor_point: Point = positions[ci];
let col: Color =
Color::hex(MERMAID_PIE_PALETTE[commit.get_lane() % MERMAID_PIE_PALETTE.len()]);
let is_hl: bool = commit
.get_commit_type()
.eq_ignore_ascii_case(MERMAID_GIT_HIGHLIGHT);
let is_rev: bool = commit
.get_commit_type()
.eq_ignore_ascii_case(MERMAID_GIT_REVERSE);
display_list.push(DrawCommand::Circle {
center: cursor_point,
radius: if is_hl { 9.5 } else { 7.5 },
color: col,
});
if is_rev {
display_list.push(DrawCommand::Circle {
center: cursor_point,
radius: 4.5,
color: eva.get_background(),
});
}
draw_centered_label(
display_list,
Rect::new(
cursor_point.get_x() - 30.0,
cursor_point.get_y() + 10.0,
60.0,
15.0,
),
commit.get_id(),
10.0,
FontWeight::Medium,
eva.get_foreground(),
TextAlign::Center,
);
if !commit.get_tag().is_empty() {
let tw: f32 = ((commit.get_tag().chars().count() as f32) * 6.5 + 14.0).max(34.0);
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
cursor_point.get_x() - tw * 0.5,
cursor_point.get_y() - 26.0,
tw,
16.0,
),
color: palette.get_warning().with_alpha(48),
radius: CornerRadius::all(4.0),
border: Border::new(1.0, palette.get_warning()),
});
draw_centered_label(
display_list,
Rect::new(
cursor_point.get_x() - tw * 0.5,
cursor_point.get_y() - 26.0,
tw,
16.0,
),
commit.get_tag(),
9.5,
FontWeight::Bold,
palette.get_foreground(),
TextAlign::Center,
);
}
}
}
fn compute_rect_anchor_points(ra: Rect, rb: Rect, horiz: bool) -> (Point, Point) {
let ax: f32 = ra.get_x() + ra.get_width() * 0.5;
let ay: f32 = ra.get_y() + ra.get_height() * 0.5;
let bx: f32 = rb.get_x() + rb.get_width() * 0.5;
let by: f32 = rb.get_y() + rb.get_height() * 0.5;
if horiz {
if bx >= ax {
(Point::new(ra.right(), ay), Point::new(rb.get_x(), by))
} else {
(Point::new(ra.get_x(), ay), Point::new(rb.right(), by))
}
} else if by >= ay {
(Point::new(ax, ra.bottom()), Point::new(bx, rb.get_y()))
} else {
(Point::new(ax, ra.get_y()), Point::new(bx, rb.bottom()))
}
}
fn draw_vector_connector(
display_list: &mut DisplayList,
from: Point,
to: Point,
color: Color,
width: f32,
dashed: bool,
arrow: bool,
) {
let dx: f32 = to.get_x() - from.get_x();
let dy: f32 = to.get_y() - from.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let line_end: Point = if arrow {
Point::new(to.get_x() - ux * 7.5, to.get_y() - uy * 7.5)
} else {
to
};
if dashed {
draw_dashed_line(display_list, from, line_end, color, width);
} else {
display_list.push(DrawCommand::Line {
from,
to: line_end,
color,
width,
});
}
if arrow {
draw_arrowhead(display_list, from, to, color);
}
}
fn draw_dashed_line(
display_list: &mut DisplayList,
from: Point,
to: Point,
color: Color,
width: f32,
) {
let dx: f32 = to.get_x() - from.get_x();
let dy: f32 = to.get_y() - from.get_y();
let len: f32 = dx.hypot(dy);
if len < 1.0 {
return;
}
let ux: f32 = dx / len;
let uy: f32 = dy / len;
let dash: f32 = 6.0;
let gap: f32 = 4.0;
let mut dist: f32 = 0.0;
while dist < len {
let seg_end: f32 = (dist + dash).min(len);
display_list.push(DrawCommand::Line {
from: Point::new(from.get_x() + ux * dist, from.get_y() + uy * dist),
to: Point::new(from.get_x() + ux * seg_end, from.get_y() + uy * seg_end),
color,
width,
});
dist += dash + gap;
}
}
fn draw_centered_label(
display_list: &mut DisplayList,
rect: Rect,
text: &str,
font_size: f32,
weight: FontWeight,
color: Color,
align: TextAlign,
) {
if text.is_empty() {
return;
}
let line_h: f32 = font_size * 1.25;
let ty: f32 = rect.get_y() + ((rect.get_height() - line_h).max(0.0)) * 0.5;
let mut style: TextStyle = TextStyle::default();
style
.set_font_size(font_size)
.set_weight(weight)
.set_color(color)
.set_align(align)
.set_overflow(TextOverflow::Clip);
display_list.push(DrawCommand::TextRun {
rect: Rect::new(rect.get_x(), ty, rect.get_width().max(8.0), line_h),
text: text.to_string(),
style,
});
}