Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 7 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/mermaid_render/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ test-support = []
[dependencies]
anyhow.workspace = true
gpui.workspace = true
merman = { version = "0.6.2", features = ["render"] }
merman = { git = "https://github.com/zed-industries/merman", tag = "v0.6.2-with-patches", features = ["render"] }
quick-xml.workspace = true
serde_json.workspace = true

Expand Down
21 changes: 21 additions & 0 deletions crates/mermaid_render/src/mermaid_render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,24 @@ pub fn render_to_svg(source: &str, theme: &MermaidTheme) -> Result<String> {
let svg = postprocess::postprocess(&svg, theme)?;
Ok(svg)
}

#[cfg(test)]
mod tests {
use super::*;

/// A flowchart with mutually nested subgraphs (`A` contains `B` and `B`
/// contains `A`) is an invalid containment cycle. Rendering it must return
/// gracefully rather than overflowing the stack and aborting the process.
#[test]
fn cyclic_subgraphs_do_not_crash() {
let source = "flowchart TD\n subgraph A\n B\n end\n subgraph B\n A\n end";
let result = render_to_svg(source, &MermaidTheme::default());
if let Err(err) = result {
let message = format!("{err:#}");
assert!(
message.contains("cycle"),
"expected a cycle-related error, got: {message}"
);
}
}
}
47 changes: 26 additions & 21 deletions crates/mermaid_render/src/postprocess/accent_colors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,14 @@ pub(crate) fn parse_path_half_height(e: &BytesStart<'_>) -> Option<f64> {
let attr = e.try_get_attribute("d").ok()??;
let d = attr.unescape_value().ok()?;
let rest = d.strip_prefix('M')?.trim_start();
let mut chars = rest.chars().peekable();
while chars.peek().is_some_and(|c| *c != ' ' && *c != ',') {
chars.next();
}
while chars.peek().is_some_and(|c| *c == ' ' || *c == ',') {
chars.next();
}
let y_str: String = chars.take_while(|c| *c != ' ' && *c != ',').collect();
let y: f64 = y_str.parse().ok()?;
// The path data starts with `M x,y ...`; the y coordinate is the second
// whitespace/comma-separated token.
let y: f64 = rest
.split([' ', ','])
.filter(|token| !token.is_empty())
.nth(1)?
.parse()
.ok()?;
Some(y.abs())
}

Expand Down Expand Up @@ -255,9 +254,9 @@ enum Handler {
Sequence(sequence_diagram::SequenceDiagramAccents),
}

struct AccentColors<I> {
struct AccentColors<'theme, I> {
inner: I,
theme: MermaidTheme,
theme: &'theme MermaidTheme,
handler: Handler,
in_legend: bool,
legend_color_idx: usize,
Expand All @@ -268,19 +267,25 @@ struct AccentColors<I> {
quadrant_point_idx: usize,
}

impl<'a, I: Iterator<Item = Result<Event<'a>>>> AccentColors<I> {
impl<'a, 'theme, I: Iterator<Item = Result<Event<'a>>>> AccentColors<'theme, I> {
fn process_chart_colors(&mut self, event: Event<'a>) -> Result<Event<'a>> {
match &event {
Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"g" => {
if self.in_plot {
let is_start = matches!(event, Event::Start(_));
// Only a real opening tag increases nesting depth. Self-closing `<g/>`
// elements have no matching `</g>`, so counting them would leave
// `plot_depth` permanently inflated and `in_plot` stuck on.
if self.in_plot && is_start {
self.plot_depth += 1;
}
if let Some(class_attr) = e.try_get_attribute("class")? {
let class = class_attr.unescape_value()?;
if class.as_ref() == "plot" {
self.in_plot = true;
self.plot_depth = 1;
self.plot_path_done = false;
if is_start && !self.in_plot {
self.in_plot = true;
self.plot_depth = 1;
self.plot_path_done = false;
}
} else if class.as_ref() == "legend" {
self.in_legend = true;
} else if class.as_ref() == "data-point" {
Expand All @@ -297,7 +302,7 @@ impl<'a, I: Iterator<Item = Result<Event<'a>>>> AccentColors<I> {

Event::End(e) if e.name().as_ref() == b"g" => {
if self.in_plot {
self.plot_depth -= 1;
self.plot_depth = self.plot_depth.saturating_sub(1);
if self.plot_depth == 0 {
self.in_plot = false;
}
Expand Down Expand Up @@ -344,7 +349,7 @@ impl<'a, I: Iterator<Item = Result<Event<'a>>>> AccentColors<I> {
}
}

impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for AccentColors<I> {
impl<'a, 'theme, I: Iterator<Item = Result<Event<'a>>>> Iterator for AccentColors<'theme, I> {
type Item = Result<Event<'a>>;

fn next(&mut self) -> Option<Self::Item> {
Expand Down Expand Up @@ -394,13 +399,13 @@ impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for AccentColors<I> {
}
}

pub(super) fn process<'a>(
pub(super) fn process<'a, 'theme>(
events: impl Iterator<Item = Result<Event<'a>>>,
theme: &MermaidTheme,
theme: &'theme MermaidTheme,
) -> impl Iterator<Item = Result<Event<'a>>> {
AccentColors {
inner: events,
theme: theme.clone(),
theme,
handler: Handler::Pending,
in_legend: false,
legend_color_idx: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,9 @@ impl MindmapAccents {
None => return Ok(None),
};
let class = class_attr.unescape_value()?;
let tokens: Vec<&str> = class.split_whitespace().collect();
let is_root = tokens.contains(&"section-root");
let is_root = class.split_whitespace().any(|t| t == "section-root");

for token in &tokens {
for token in class.split_whitespace() {
if let Some(rest) = token.strip_prefix("section-") {
if rest == "-1" || rest.parse::<u32>().is_ok() {
let class_name = if is_root {
Expand Down
3 changes: 2 additions & 1 deletion crates/mermaid_render/src/postprocess/element_fixup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,11 @@ fn rewrite_background_style<'a>(style: &'a str, background_css: &str) -> Cow<'a,
return Cow::Borrowed(style);
}

let value_len = value_end.saturating_sub(value_start);
let mut rewritten = String::with_capacity(
style
.len()
.saturating_sub(value_end - value_start)
.saturating_sub(value_len)
.saturating_add(background_css.len()),
);
rewritten.push_str(&style[..value_start]);
Expand Down
24 changes: 8 additions & 16 deletions crates/mermaid_render/src/postprocess/inject_css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,22 +108,14 @@ pub(super) fn process<'a>(
}

fn mindmap_section_css(theme: &MermaidTheme) -> String {
let colors: Vec<String> = theme
.git_branch_colors
.iter()
.map(|c| crate::css_color(*c))
.collect();
let fills: Vec<String> = theme
.git_branch_colors
.iter()
.map(|c| {
crate::css_color(blend_over_background(
*c,
theme.background,
ACCENT_FILL_OPACITY,
))
})
.collect();
let colors: [String; 8] = theme.git_branch_colors.map(crate::css_color);
let fills: [String; 8] = theme.git_branch_colors.map(|c| {
crate::css_color(blend_over_background(
c,
theme.background,
ACCENT_FILL_OPACITY,
))
});
let text = crate::css_color(theme.text_color);
let mut css = String::with_capacity(5_400);

Expand Down
10 changes: 8 additions & 2 deletions crates/mermaid_render/src/postprocess/strip_foreignobject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl<'a, I> StripForeignObject<'a, I> {
fn buffer_fallback_event(&mut self, event: Event<'a>) {
match &event {
Event::Start(_) => self.fallback_depth += 1,
Event::End(_) => self.fallback_depth -= 1,
Event::End(_) => self.fallback_depth = self.fallback_depth.saturating_sub(1),
Event::Text(t) => {
if let Ok(decoded) = t.decode() {
self.buffered_text.push_str(&decoded);
Expand Down Expand Up @@ -188,10 +188,16 @@ pub(super) fn process<'a>(
inner: impl Iterator<Item = Result<Event<'a>>>,
svg: &str,
) -> impl Iterator<Item = Result<Event<'a>>> {
// if there's no foreignobjects,
let native_text_contents = if svg.contains("data-merman-foreignobject=\"fallback\"") {
collect_native_text_contents(svg)
} else {
HashSet::new()
};
StripForeignObject {
inner,
foreign_depth: 0,
native_text_contents: collect_native_text_contents(svg),
native_text_contents,
buffer: Vec::new(),
fallback_depth: 0,
buffered_text: String::new(),
Expand Down
11 changes: 6 additions & 5 deletions crates/mermaid_render/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,12 @@ fn to_merman_config(theme: &MermaidTheme) -> merman::MermaidConfig {
"quadrantInternalBorderStrokeFill": primary_border,
});

let map = theme_vars.as_object_mut().expect("just created as object");
for i in 0..8 {
map.insert(format!("cScale{i}"), git[i].clone().into());
map.insert(format!("cScaleLabel{i}"), git_lbl[i].clone().into());
map.insert(format!("pie{}", i + 1), git[i].clone().into());
if let Some(map) = theme_vars.as_object_mut() {
for (((i, color), label), pie_number) in git.iter().enumerate().zip(&git_lbl).zip(1..) {
map.insert(format!("cScale{i}"), color.clone().into());
map.insert(format!("cScaleLabel{i}"), label.clone().into());
map.insert(format!("pie{pie_number}"), color.clone().into());
}
}

merman::MermaidConfig::from_value(serde_json::json!({
Expand Down
Loading