Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

markdown: Update merman renderer to 0.6 (#57967)

Latias946d72acdb9911
diff --git a/Cargo.lock b/Cargo.lock
index fee93d375bd..3542c4a1993 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5380,8 +5380,9 @@ dependencies = [
[[package]]
name = "dugong"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a6170733f3de44de3cf86a6b2ce4a6adfa2d0fcc546d0298896c36b4675c783"
dependencies = [
"dugong-graphlib",
"rustc-hash 2.1.1",
@@ -5391,8 +5392,9 @@ dependencies = [
[[package]]
name = "dugong-graphlib"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5620a3975d89a161bbb99c2e6cf5fbfb692de86499cc1bea3e570db2e7637394"
dependencies = [
"hashbrown 0.16.1",
"rustc-hash 2.1.1",
@@ -10553,8 +10555,9 @@ dependencies = [
[[package]]
name = "manatee"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6edb0293fd8cd549e79426a441354ee13e7b9b2136d2aa30ccba99861b229f14"
dependencies = [
"indexmap 2.11.4",
"nalgebra",
@@ -10848,8 +10851,9 @@ dependencies = [
[[package]]
name = "merman"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7f9f0f65e455090527adc4bcc6b7c917fa2fb3d29c7d8f8fe180ae8a1295d76"
dependencies = [
"merman-core",
"merman-render",
@@ -10858,8 +10862,9 @@ dependencies = [
[[package]]
name = "merman-core"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7975b707ca62dc6e0585e89c6e45c4d788b277d13c2501197d00d9b9c52350bc"
dependencies = [
"chrono",
"euclid",
@@ -10884,8 +10889,9 @@ dependencies = [
[[package]]
name = "merman-render"
-version = "0.4.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e155e441addf61cbdd00c1a6e4e59a199aab6401110b46ae621b035673455c2b"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -15367,7 +15373,8 @@ dependencies = [
[[package]]
name = "roughr-merman"
version = "0.12.0"
-source = "git+https://github.com/zed-industries/merman?rev=1c765dcca2ef5092fcde7bebe8374819563623ef#1c765dcca2ef5092fcde7bebe8374819563623ef"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c34fd013a888d8b2119b3ed57cd3df0f1f9dd2db3fa94fdb98f58d60f9855ef0"
dependencies = [
"derive_builder",
"euclid",
diff --git a/crates/mermaid_render/Cargo.toml b/crates/mermaid_render/Cargo.toml
index 6706e028d1d..a64be8bc2eb 100644
--- a/crates/mermaid_render/Cargo.toml
+++ b/crates/mermaid_render/Cargo.toml
@@ -18,7 +18,7 @@ test-support = []
[dependencies]
anyhow.workspace = true
gpui.workspace = true
-merman = { git = "https://github.com/zed-industries/merman", rev = "1c765dcca2ef5092fcde7bebe8374819563623ef", features = ["render"] }
+merman = { version = "0.6.2", features = ["render"] }
quick-xml.workspace = true
serde_json.workspace = true
diff --git a/crates/mermaid_render/src/mermaid_render.rs b/crates/mermaid_render/src/mermaid_render.rs
index 1e17d8d780b..eaf752ceff3 100644
--- a/crates/mermaid_render/src/mermaid_render.rs
+++ b/crates/mermaid_render/src/mermaid_render.rs
@@ -16,20 +16,21 @@
//!
//! This module uses the [`merman`] crate for rendering, rather than
//! `mermaid-rs`, which was used in the previous implementation of mermaid
-//! rendering in Zed. Merman provides significantly more accurate rendering, and
-//! seems to be somewhat faster, but by default has poor CSS, making diagrams
-//! look weird without significant cleanup. This is made worse by the fact that
-//! `usvg`/`resvg` doesn't support some features that [`merman`] relies on.
+//! rendering in Zed.
//!
-//! As such, this crate is quite large. But the code is very self-contained, and
-//! has few dependencies. In fact, the [`gpui`] dependency is only needed for
-//! the [`Hsla`] and [`Rgba`] color types.
+//! Historically, this crate also carried generic `usvg`/`resvg` cleanup for SVG
+//! constructs that merman's parity output could emit, such as HTML labels in
+//! `<foreignObject>` and CSS/attribute forms that rasterizers do not handle.
+//! Since merman 0.6, that generic cleanup is exposed as merman's raster-safe SVG
+//! pipeline. Zed opts into that pipeline during rendering, then keeps
+//! editor-specific theme and accent color rules in this crate. The [`gpui`]
+//! dependency is only needed for the [`Hsla`] and [`Rgba`] color types.
//!
//! The [`render_to_svg`] function operates in two stages:
-//! - [`render`] the mermaid text to SVG using [`merman`].
-//! - [`postprocess`] the SVG to clean incorrect output and add styling.
+//! - [`render`] the mermaid text to raster-safe SVG using [`merman`].
+//! - [`postprocess`] the SVG to add Zed theme and accent styling.
//!
-//! The postprocessing is also split up into stages. We parse the generated SVG
+//! Zed's postprocessing is split up into stages. We parse the generated SVG
//! using [`quick_xml`], which produces an iterator of
//! [`Event<'_>`](quick_xml::events::Event)s. This iterator is then repeatedly
//! transformed, and finally collected back into an SVG string.
diff --git a/crates/mermaid_render/src/postprocess.rs b/crates/mermaid_render/src/postprocess.rs
index af1e61f3367..1f3b818c47f 100644
--- a/crates/mermaid_render/src/postprocess.rs
+++ b/crates/mermaid_render/src/postprocess.rs
@@ -1,4 +1,4 @@
-//! Post-processing of [`merman`]-produced SVGs for rasterization with `usvg`/`resvg`.
+//! Zed-specific post-processing of [`merman`]-produced SVGs.
//!
//! Each submodule is a specific pass that tweaks the SVG event iterator in a particular way.
//!
@@ -13,11 +13,8 @@
mod accent_colors;
mod element_fixup;
-mod fallback_fixup;
-mod foreignobject_wrap;
mod inject_css;
mod strip_foreignobject;
-mod strip_invalid_css;
pub(crate) mod util;
use anyhow::{Context as _, Result};
@@ -27,27 +24,21 @@ use quick_xml::events::Event;
use crate::MermaidTheme;
pub(super) fn postprocess(svg: &str, theme: &MermaidTheme) -> Result<String> {
- // Pass 1: foreignObject preparation (\n fix + word wrapping)
- let svg = foreignobject_wrap::process(svg)?;
+ // merman 0.6 already applies the generic resvg-safe cleanup before this point.
+ // The remaining passes are Zed-specific theme and accent adjustments.
+ let svg_id = extract_svg_id(svg);
- // Add <text> fallbacks alongside <foreignObject> elements
- let svg = merman::render::foreign_object_label_fallback_svg_text(&svg);
-
- // Extract SVG id for CSS scoping (quick scan of the first element)
- let svg_id = extract_svg_id(&svg);
-
- // Pass 2: themed post-processing pipeline.
- // Each adapter takes an iterator of events and returns an iterator of events.
- // Events borrow from the `svg` string — no .into_owned() per event.
- let mut reader = Reader::from_str(&svg);
+ let mut reader = Reader::from_str(svg);
reader.config_mut().check_end_names = false;
let events = ReaderIter::new(reader);
- let events = strip_foreignobject::process(events);
- let events = fallback_fixup::process(events, theme);
+ // merman's resvg-safe pipeline already removes foreignObject elements and
+ // replaces their labels with native <text> fallback groups. This pass keeps
+ // those fallback labels, but drops any that merely duplicate a native
+ // <text> (e.g. user journey renders some labels both ways).
+ let events = strip_foreignobject::process(events, svg);
let events = element_fixup::process(events, theme);
let events = accent_colors::process(events, theme);
- let events = strip_invalid_css::process(events);
let events = inject_css::process(events, theme, &svg_id);
let mut writer = quick_xml::Writer::new(Vec::with_capacity(svg.len()));
@@ -111,26 +102,3 @@ impl<'a> Iterator for ReaderIter<'a> {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn default_theme() -> MermaidTheme {
- MermaidTheme::default()
- }
-
- #[test]
- fn strip_css_handles_style_element_with_attributes() {
- let svg = r#"<svg id="test" xmlns="http://www.w3.org/2000/svg"><style type="text/css">@keyframes bounce { 0% { transform: scale(1); } 100% { transform: scale(1.1); } } .node rect { fill: red; }</style><rect width="10" height="10"/></svg>"#;
- let result = postprocess(svg, &default_theme()).unwrap();
- assert!(
- !result.contains("@keyframes"),
- "Unsupported @keyframes should be stripped from <style type=\"text/css\">, got: {result}"
- );
- assert!(
- result.contains(".node rect"),
- "Regular CSS rules should survive stripping, got: {result}"
- );
- }
-}
diff --git a/crates/mermaid_render/src/postprocess/accent_colors.rs b/crates/mermaid_render/src/postprocess/accent_colors.rs
index 3e811b4dce3..795abd2fdb3 100644
--- a/crates/mermaid_render/src/postprocess/accent_colors.rs
+++ b/crates/mermaid_render/src/postprocess/accent_colors.rs
@@ -144,8 +144,48 @@ pub(crate) fn add_class<'a>(e: &BytesStart<'_>, class_to_add: &str) -> Result<By
Ok(new_elem)
}
-pub(crate) fn current_stack_accent(stack: &[Option<usize>]) -> Option<usize> {
- stack.iter().rev().find_map(|entry| *entry)
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct AccentStackEntry {
+ /// The accent inherited by nested text, even when the group has no layout geometry.
+ accent_idx: Option<usize>,
+ /// Whether this group called `NodeTracker::start_node` and must be finished later.
+ tracks_node: bool,
+}
+
+impl AccentStackEntry {
+ pub fn none() -> Self {
+ Self {
+ accent_idx: None,
+ tracks_node: false,
+ }
+ }
+
+ pub fn accent(accent_idx: usize, tracks_node: bool) -> Self {
+ Self {
+ accent_idx: Some(accent_idx),
+ tracks_node,
+ }
+ }
+
+ pub fn tracks_node(self) -> bool {
+ self.tracks_node
+ }
+
+ fn accent_idx(self) -> Option<usize> {
+ self.accent_idx
+ }
+}
+
+pub(crate) fn current_stack_accent(stack: &[AccentStackEntry]) -> Option<usize> {
+ stack.iter().rev().find_map(|entry| entry.accent_idx())
+}
+
+// merman's fallback overlay groups intentionally preserve source classes such
+// as `node` and `section-*` so host CSS can style fallback text. They are not
+// layout nodes though, so accent tracking must not count them as new nodes.
+pub(crate) fn is_foreign_object_fallback_group(e: &BytesStart<'_>) -> Result<bool> {
+ Ok(e.try_get_attribute("data-merman-foreignobject")?
+ .is_some_and(|attr| attr.value.as_ref() == b"fallback"))
}
pub(crate) fn lookup_position_accent(node_rects: &[NodeRect], e: &BytesStart<'_>) -> Option<usize> {
diff --git a/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs b/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs
index 17861673bb0..6c7d019c38c 100644
--- a/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs
+++ b/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs
@@ -1,11 +1,14 @@
use anyhow::Result;
use quick_xml::events::Event;
-use super::{NodeTracker, accent_class_name, add_class, add_to_event, parse_translate};
+use super::{
+ AccentStackEntry, NodeTracker, accent_class_name, add_class, add_to_event,
+ is_foreign_object_fallback_group, parse_translate,
+};
pub(crate) struct ClassDiagramAccents {
accent_count: usize,
- accent_g_stack: Vec<Option<usize>>,
+ accent_g_stack: Vec<AccentStackEntry>,
node_counter: usize,
nodes: NodeTracker,
current_text_accent: Option<usize>,
@@ -29,6 +32,11 @@ impl ClassDiagramAccents {
match &event {
Event::Start(e) if e.name().as_ref() == b"g" => {
+ if is_foreign_object_fallback_group(e)? {
+ self.accent_g_stack.push(AccentStackEntry::none());
+ return Ok(event);
+ }
+
let is_node = if let Some(class_attr) = e.try_get_attribute("class")? {
let class = class_attr.unescape_value()?;
class
@@ -42,22 +50,26 @@ impl ClassDiagramAccents {
let accent_idx = self.node_counter % self.accent_count;
self.node_counter += 1;
- if let Some((cx, cy)) = parse_translate(e) {
+ let tracks_node = if let Some((cx, cy)) = parse_translate(e) {
self.nodes.start_node(cx, cy, 30.0, accent_idx);
- }
+ true
+ } else {
+ false
+ };
- self.accent_g_stack.push(Some(accent_idx));
+ self.accent_g_stack
+ .push(AccentStackEntry::accent(accent_idx, tracks_node));
let new_elem = add_class(e, &accent_class_name(accent_idx))?;
return Ok(Event::Start(new_elem));
}
- self.accent_g_stack.push(None);
+ self.accent_g_stack.push(AccentStackEntry::none());
Ok(event)
}
Event::End(e) if e.name().as_ref() == b"g" => {
if let Some(entry) = self.accent_g_stack.pop() {
- if entry.is_some() {
+ if entry.tracks_node() {
self.nodes.maybe_finish_node();
}
}
diff --git a/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs b/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs
index 016571790a6..d7cf6901a2f 100644
--- a/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs
+++ b/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs
@@ -1,11 +1,11 @@
use anyhow::Result;
use quick_xml::events::{BytesStart, Event};
-use super::NodeTracker;
+use super::{AccentStackEntry, NodeTracker};
pub(super) struct MindmapAccents {
section_classes: Vec<String>,
- section_g_stack: Vec<Option<usize>>,
+ section_g_stack: Vec<AccentStackEntry>,
nodes: NodeTracker,
current_text_section: Option<usize>,
}
@@ -23,21 +23,30 @@ impl MindmapAccents {
pub(super) fn process_event<'a>(&mut self, event: Event<'a>) -> Result<Event<'a>> {
match &event {
Event::Start(e) if e.name().as_ref() == b"g" => {
+ if super::is_foreign_object_fallback_group(e)? {
+ self.section_g_stack.push(AccentStackEntry::none());
+ return Ok(event);
+ }
+
let section_idx = self.parse_section_class(e)?;
if let Some(idx) = section_idx {
- if let Some((tx, ty)) = super::parse_translate(e) {
+ let tracks_node = if let Some((tx, ty)) = super::parse_translate(e) {
self.nodes.start_node(tx, ty, 0.0, idx);
- }
- self.section_g_stack.push(Some(idx));
+ true
+ } else {
+ false
+ };
+ self.section_g_stack
+ .push(AccentStackEntry::accent(idx, tracks_node));
} else {
- self.section_g_stack.push(None);
+ self.section_g_stack.push(AccentStackEntry::none());
}
Ok(event)
}
Event::End(e) if e.name().as_ref() == b"g" => {
- if let Some(maybe_section) = self.section_g_stack.pop() {
- if maybe_section.is_some() {
+ if let Some(entry) = self.section_g_stack.pop() {
+ if entry.tracks_node() {
self.nodes.maybe_finish_node();
}
}
diff --git a/crates/mermaid_render/src/postprocess/element_fixup.rs b/crates/mermaid_render/src/postprocess/element_fixup.rs
index 470da4f9c6a..2f93c45b0b4 100644
--- a/crates/mermaid_render/src/postprocess/element_fixup.rs
+++ b/crates/mermaid_render/src/postprocess/element_fixup.rs
@@ -102,22 +102,33 @@ fn font_style(font_family: &str) -> String {
}
fn rewrite_background_style<'a>(style: &'a str, background_css: &str) -> Cow<'a, str> {
- const WHITE_BACKGROUND_STYLE: &str = "background-color: white";
+ const PROPERTY: &str = "background-color:";
- let Some(background_start) = style.find(WHITE_BACKGROUND_STYLE) else {
+ let Some(property_start) = style.find(PROPERTY) else {
return Cow::Borrowed(style);
};
+ let value_start = property_start + PROPERTY.len();
+ let value_end = style[value_start..]
+ .find(';')
+ .map_or(style.len(), |offset| value_start + offset);
+ let value = style[value_start..value_end].trim();
+
+ let is_white = value.eq_ignore_ascii_case("white")
+ || value.eq_ignore_ascii_case("#fff")
+ || value.eq_ignore_ascii_case("#ffffff");
+ if !is_white {
+ return Cow::Borrowed(style);
+ }
let mut rewritten = String::with_capacity(
style
.len()
- .saturating_sub(WHITE_BACKGROUND_STYLE.len())
- .saturating_add("background-color: ".len())
+ .saturating_sub(value_end - value_start)
.saturating_add(background_css.len()),
);
- rewritten.push_str(&style[..background_start]);
- write!(rewritten, "background-color: {background_css}").expect("write to String cannot fail");
- rewritten.push_str(&style[background_start + WHITE_BACKGROUND_STYLE.len()..]);
+ rewritten.push_str(&style[..value_start]);
+ rewritten.push_str(background_css);
+ rewritten.push_str(&style[value_end..]);
Cow::Owned(rewritten)
}
diff --git a/crates/mermaid_render/src/postprocess/fallback_fixup.rs b/crates/mermaid_render/src/postprocess/fallback_fixup.rs
deleted file mode 100644
index 2ae1f86f2d5..00000000000
--- a/crates/mermaid_render/src/postprocess/fallback_fixup.rs
+++ /dev/null
@@ -1,223 +0,0 @@
-//! Fixes double-escaped HTML entities inside fallback `<text>` groups that
-//! were generated as replacements for `<foreignObject>` content.
-//!
-//! ```xml
-//! <!-- before -->
-//! <g data-merman-foreignobject="fallback">
-//! <text>List&amp;lt;T&amp;gt;</text>
-//! </g>
-//!
-//! <!-- after -->
-//! <g data-merman-foreignobject="fallback">
-//! <text>List&lt;T&gt;</text>
-//! </g>
-//! ```
-
-use std::collections::VecDeque;
-
-use anyhow::Result;
-
-use quick_xml::events::{BytesStart, BytesText, Event};
-
-use crate::MermaidTheme;
-
-struct FallbackFixup<'a, I> {
- inner: I,
- edge_label_bg: String,
- fallback_depth: usize,
- text_buffer: String,
- output_queue: VecDeque<Event<'a>>,
-}
-
-impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for FallbackFixup<'a, I> {
- type Item = Result<Event<'a>>;
-
- fn next(&mut self) -> Option<Self::Item> {
- if let Some(event) = self.output_queue.pop_front() {
- return Some(Ok(event));
- }
-
- loop {
- let event = match self.inner.next()? {
- Ok(ev) => ev,
- Err(e) => return Some(Err(e)),
- };
-
- match &event {
- Event::Start(e) if e.name().as_ref() == b"g" => {
- if self.fallback_depth > 0 {
- self.fallback_depth += 1;
- } else {
- match e.try_get_attribute("data-merman-foreignobject") {
- Ok(Some(attr)) if attr.value.as_ref() == b"fallback" => {
- self.fallback_depth = 1;
- }
- Err(e) => return Some(Err(e.into())),
- _ => {}
- }
- }
- }
- Event::End(e) if e.name().as_ref() == b"g" && self.fallback_depth > 0 => {
- self.flush_text_buffer();
- self.fallback_depth -= 1;
- }
- _ => {}
- }
-
- if self.fallback_depth == 0 {
- return Some(Ok(event));
- }
-
- // Inside fallback group: accumulate text-like events, process others
- match &event {
- Event::Text(t) => {
- match std::str::from_utf8(t.as_ref()) {
- Ok(raw) => self.text_buffer.push_str(raw),
- Err(e) => eprintln!("Invalid UTF-8 in fallback text: {e}"),
- }
- continue;
- }
- Event::GeneralRef(r) => {
- self.text_buffer.push('&');
- match std::str::from_utf8(r.as_ref()) {
- Ok(name) => self.text_buffer.push_str(name),
- Err(e) => eprintln!("Invalid UTF-8 in fallback entity ref: {e}"),
- }
- self.text_buffer.push(';');
- continue;
- }
- _ => {}
- }
-
- self.flush_text_buffer();
-
- match self.process_non_text_event(event) {
- Ok(ev) => self.output_queue.push_back(ev),
- Err(e) => return Some(Err(e)),
- }
-
- if let Some(event) = self.output_queue.pop_front() {
- return Some(Ok(event));
- }
- }
- }
-}
-
-impl<'a, I> FallbackFixup<'a, I> {
- fn flush_text_buffer(&mut self) {
- if self.text_buffer.is_empty() {
- return;
- }
- let text = if self.text_buffer.contains("&amp;lt;") || self.text_buffer.contains("&amp;gt;")
- {
- let fixed = self
- .text_buffer
- .replace("&amp;lt;", "&lt;")
- .replace("&amp;gt;", "&gt;");
- self.text_buffer.clear();
- fixed
- } else {
- std::mem::take(&mut self.text_buffer)
- };
- self.output_queue
- .push_back(Event::Text(BytesText::from_escaped(text)));
- }
-
- fn process_non_text_event(&self, event: Event<'a>) -> Result<Event<'a>> {
- let is_start = matches!(event, Event::Start(_));
- match &event {
- Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"rect" => {
- let mut new_elem = BytesStart::new("rect");
- for attr in e.attributes() {
- let attr = attr?;
- if attr.key.local_name().as_ref() == b"fill" {
- new_elem.push_attribute(("fill", self.edge_label_bg.as_str()));
- } else {
- new_elem.push_attribute(attr);
- }
- }
- Ok(if is_start {
- Event::Start(new_elem)
- } else {
- Event::Empty(new_elem)
- })
- }
- _ => Ok(event),
- }
- }
-}
-
-pub(super) fn process<'a>(
- events: impl Iterator<Item = Result<Event<'a>>>,
- theme: &MermaidTheme,
-) -> impl Iterator<Item = Result<Event<'a>>> {
- let edge_label_bg = crate::css_color(theme.edge_label_background);
- FallbackFixup {
- inner: events,
- edge_label_bg,
- fallback_depth: 0,
- text_buffer: String::new(),
- output_queue: VecDeque::new(),
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use quick_xml::Reader;
-
- fn run_fixup(svg: &str) -> String {
- let reader = Reader::from_str(svg);
- let events = std::iter::from_fn({
- let mut reader = reader;
- let mut done = false;
- move || {
- if done {
- return None;
- }
- match reader.read_event() {
- Ok(quick_xml::events::Event::Eof) => {
- done = true;
- None
- }
- Ok(ev) => Some(Ok(ev)),
- Err(e) => {
- done = true;
- Some(Err(e.into()))
- }
- }
- }
- });
- let theme = crate::MermaidTheme::default();
- let fixed = process(events, &theme);
- let mut writer = quick_xml::Writer::new(Vec::new());
- for ev in fixed {
- writer.write_event(ev.unwrap()).unwrap();
- }
- String::from_utf8(writer.into_inner()).unwrap()
- }
-
- #[test]
- fn fixes_double_escaped_entities_in_fallback() {
- let svg = r##"<g data-merman-foreignobject="fallback"><text fill="#333">-List&amp;lt;Animal&amp;gt; animals</text></g>"##;
- let result = run_fixup(svg);
- assert!(
- !result.contains("&amp;lt;"),
- "Should fix double-escaped entities, got: {result}"
- );
- assert!(
- result.contains("&lt;"),
- "Should contain single-escaped entity, got: {result}"
- );
- }
-
- #[test]
- fn preserves_text_outside_fallback_group() {
- let svg = r##"<text>-List&amp;lt;Animal&amp;gt;</text>"##;
- let result = run_fixup(svg);
- assert!(
- result.contains("&amp;lt;"),
- "Should not fix entities outside fallback group, got: {result}"
- );
- }
-}
diff --git a/crates/mermaid_render/src/postprocess/foreignobject_wrap.rs b/crates/mermaid_render/src/postprocess/foreignobject_wrap.rs
deleted file mode 100644
index 2c2e1d91254..00000000000
--- a/crates/mermaid_render/src/postprocess/foreignobject_wrap.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-//! Converts literal `\n` escape sequences inside `<foreignObject>` elements
-//! into `<br/>` tags so that line breaks render correctly.
-//!
-//! ```xml
-//! <!-- before -->
-//! <foreignObject>Hello\nWorld</foreignObject>
-//!
-//! <!-- after -->
-//! <foreignObject>Hello<br/>World</foreignObject>
-//! ```
-
-use anyhow::{Context as _, Result};
-use quick_xml::escape;
-use quick_xml::events::{BytesStart, BytesText, Event};
-use quick_xml::{Reader, Writer};
-
-pub(super) fn process(svg: &str) -> Result<String> {
- let mut reader = Reader::from_str(svg);
- reader.config_mut().check_end_names = false;
- let mut writer = Writer::new(Vec::with_capacity(svg.len()));
-
- let mut foreign_object_depth: usize = 0;
- let mut buffer = Vec::new();
-
- loop {
- let event = match reader.read_event() {
- Ok(Event::Eof) => break,
- Ok(event) => event,
- Err(e) => return Err(e).context("failed to parse SVG in foreignObject wrap pass"),
- };
-
- let is_fo_start =
- matches!(&event, Event::Start(e) if e.name().as_ref() == b"foreignObject");
- let is_fo_end = matches!(&event, Event::End(e) if e.name().as_ref() == b"foreignObject");
-
- if is_fo_start {
- if foreign_object_depth == 0 {
- buffer.clear();
- }
- buffer.push(event);
- foreign_object_depth += 1;
- } else if is_fo_end {
- foreign_object_depth = foreign_object_depth.saturating_sub(1);
- buffer.push(event);
- if foreign_object_depth == 0 {
- emit_buffered(std::mem::take(&mut buffer), &mut writer)?;
- }
- } else if foreign_object_depth > 0 {
- buffer.push(event);
- } else {
- writer.write_event(event)?;
- }
- }
-
- String::from_utf8(writer.into_inner()).context("SVG output is not valid UTF-8")
-}
-
-fn emit_buffered(buffer: Vec<Event<'_>>, writer: &mut Writer<Vec<u8>>) -> Result<()> {
- for event in buffer {
- match event {
- Event::Text(t) => {
- let processed = {
- let decoded = t.decode().unwrap_or_default();
- let text = escape::unescape(&decoded).unwrap_or_else(|_| decoded.clone());
- emit_text_content(&text, writer)?
- };
- if !processed {
- writer.write_event(Event::Text(t))?;
- }
- }
- other => {
- writer.write_event(other)?;
- }
- }
- }
- Ok(())
-}
-
-fn emit_text_content(text: &str, writer: &mut Writer<Vec<u8>>) -> Result<bool> {
- if !text.contains("\\n") {
- return Ok(false);
- }
-
- let mut first_segment = true;
- for segment in text.split("\\n") {
- if !first_segment {
- writer.write_event(Event::Empty(BytesStart::new("br")))?;
- }
- first_segment = false;
- writer.write_event(Event::Text(BytesText::from_escaped(escape::escape(
- segment,
- ))))?;
- }
-
- Ok(true)
-}
diff --git a/crates/mermaid_render/src/postprocess/inject_css.rs b/crates/mermaid_render/src/postprocess/inject_css.rs
index cd6ea4ba343..830459e942c 100644
--- a/crates/mermaid_render/src/postprocess/inject_css.rs
+++ b/crates/mermaid_render/src/postprocess/inject_css.rs
@@ -415,8 +415,8 @@ fn build_injected_css(theme: &MermaidTheme, svg_id: &str) -> String {
.cluster-label, .nodeLabel {{ color: {text} !important; }}
defs #statediagram-barbEnd {{ fill: {line} !important; stroke: {line} !important; }}
#statediagram-barbEnd {{ fill: {line} !important; }}
- .edgeLabel .label rect {{ fill: {primary} !important; }}
- .edgeLabel rect {{ fill: {primary} !important; background-color: {primary} !important; }}
+ .edgeLabel .label rect {{ fill: {edge_label_bg} !important; opacity: 1 !important; }}
+ .edgeLabel rect {{ fill: {edge_label_bg} !important; opacity: 1 !important; background-color: {edge_label_bg} !important; }}
.edgeLabel .label text {{ fill: {text} !important; }}
.edgeLabel p {{ background-color: {primary} !important; }}
.edgeLabel {{ background-color: {primary} !important; }}
@@ -447,7 +447,7 @@ fn build_injected_css(theme: &MermaidTheme, svg_id: &str) -> String {
text.journey-section, text.task {{ fill: {text} !important; }}
.relationshipLabelBox {{ fill: {tertiary} !important; opacity: 0.7; background-color: {tertiary} !important; }}
.labelBkg {{ background-color: {tertiary} !important; }}
- .edgeLabel .label {{ fill: {border} !important; }}
+ .edgeLabel .label {{ fill: {text} !important; }}
.label {{ color: {text} !important; }}
.relationshipLine {{ stroke: {line} !important; fill: none !important; }}
.entityBox {{ fill: {primary}; stroke: {border}; }}
@@ -484,7 +484,7 @@ fn build_injected_css(theme: &MermaidTheme, svg_id: &str) -> String {
.commit-merge {{ stroke: {primary}; fill: {primary}; }}
.commit-reverse {{ stroke: {primary}; fill: {primary}; stroke-width: 3; }}
.commit-highlight-inner {{ stroke: {primary}; fill: {primary}; }}
- .tag-label {{ font-size: 10px; }}
+ .tag-label {{ font-size: 10px; fill: {text}; }}
.tag-label-bkg {{ fill: {primary}; stroke: {border}; }}
.tag-hole {{ fill: {line}; }}
.commit-label {{ fill: {text}; }}
diff --git a/crates/mermaid_render/src/postprocess/strip_foreignobject.rs b/crates/mermaid_render/src/postprocess/strip_foreignobject.rs
index 8935c73e392..fb1ce644fc5 100644
--- a/crates/mermaid_render/src/postprocess/strip_foreignobject.rs
+++ b/crates/mermaid_render/src/postprocess/strip_foreignobject.rs
@@ -1,42 +1,113 @@
-//! Strips `<foreignObject>` elements and their contents from the SVG, since
-//! `usvg`/`resvg` does not support them.
+//! Strips `<foreignObject>` elements and de-duplicates redundant fallback label
+//! groups from the SVG.
+//!
+//! merman's raster-safe SVG pipeline converts `<foreignObject>` labels into
+//! native `<text>` fallback groups (`data-merman-foreignobject="fallback"`) and
+//! removes the original `<foreignObject>` elements before Zed-specific
+//! post-processing runs. For most diagram types the fallback `<text>` group is
+//! the *only* remaining copy of a label, so it must be preserved.
+//!
+//! However, some diagram types (e.g. user journey) render a label as a real
+//! native `<text>` element *and* also wrap it in a `<foreignObject>` that
+//! becomes a fallback group. Rasterizing both produces the same label twice at
+//! slightly different sizes. To avoid that, we drop a fallback group only when
+//! its text content duplicates a native (non-fallback) `<text>` elsewhere in the
+//! diagram. Fallback groups whose label has no native twin are always kept.
//!
//! ```xml
//! <!-- before -->
-//! <foreignObject><div>Hello</div></foreignObject>
-//! <text class="nodeLabel">Hello</text>
+//! <text class="task">Make tea</text>
+//! <g data-merman-foreignobject="fallback"><text>Make tea</text></g>
//!
//! <!-- after -->
-//! <text class="nodeLabel">Hello</text>
+//! <text class="task">Make tea</text>
//! ```
+use std::collections::{HashSet, VecDeque};
+
use anyhow::Result;
+use quick_xml::Reader;
use quick_xml::events::Event;
-struct StripForeignObject<I> {
+use super::ReaderIter;
+
+const FALLBACK_TEXT_CLASS: &str = "merman-foreignobject-fallback-text";
+
+/// Collects the trimmed text content of every native (non-fallback) `<text>`
+/// element. Fallback groups whose label matches one of these are duplicates.
+fn collect_native_text_contents(svg: &str) -> HashSet<String> {
+ let mut contents = HashSet::new();
+ let mut reader = Reader::from_str(svg);
+ reader.config_mut().check_end_names = false;
+
+ let mut in_native_text = false;
+ let mut current = String::new();
+ for event in ReaderIter::new(reader) {
+ match event {
+ Ok(Event::Start(e)) if e.name().as_ref() == b"text" => {
+ in_native_text = !is_fallback_text(&e);
+ current.clear();
+ }
+ Ok(Event::Text(t)) if in_native_text => {
+ if let Ok(decoded) = t.decode() {
+ current.push_str(&decoded);
+ }
+ }
+ Ok(Event::End(e)) if e.name().as_ref() == b"text" => {
+ if in_native_text {
+ let trimmed = current.trim();
+ if !trimmed.is_empty() {
+ contents.insert(trimmed.to_string());
+ }
+ }
+ in_native_text = false;
+ }
+ _ => {}
+ }
+ }
+ contents
+}
+
+fn is_fallback_text(e: &quick_xml::events::BytesStart<'_>) -> bool {
+ e.try_get_attribute("class")
+ .ok()
+ .flatten()
+ .and_then(|a| a.unescape_value().ok())
+ .is_some_and(|v| v.split_whitespace().any(|c| c == FALLBACK_TEXT_CLASS))
+}
+
+struct StripForeignObject<'a, I> {
inner: I,
/// Depth inside a `<foreignObject>` element being stripped.
foreign_depth: usize,
- /// Depth inside a `<g data-merman-foreignobject="fallback">` being stripped.
+ /// Trimmed contents of native `<text>` elements; fallback groups whose label
+ /// matches one of these are dropped as duplicates.
+ native_text_contents: HashSet<String>,
+ /// Buffered events of the fallback group currently being inspected, plus the
+ /// nesting depth within it and its accumulated text content.
+ buffer: Vec<Event<'a>>,
fallback_depth: usize,
- /// Set to true once we see a `<text>` element outside of foreignObjects
- /// and fallback groups. When true, fallback groups are redundant and
- /// should be stripped.
- has_native_text: bool,
+ buffered_text: String,
+ /// Events ready to emit (a flushed, non-duplicate fallback group).
+ output: VecDeque<Event<'a>>,
}
-impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for StripForeignObject<I> {
+impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for StripForeignObject<'a, I> {
type Item = Result<Event<'a>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
- let event = self.inner.next()?;
- let event = match event {
+ if let Some(event) = self.output.pop_front() {
+ return Some(Ok(event));
+ }
+
+ let event = match self.inner.next()? {
Ok(event) => event,
Err(e) => return Some(Err(e)),
};
- // Strip foreignObject elements and their contents.
+ // Strip foreignObject elements and their contents (defensive: merman
+ // already removes them, but a stray one cannot be rasterized).
match &event {
Event::Start(e) if e.name().as_ref() == b"foreignObject" => {
self.foreign_depth += 1;
@@ -59,56 +130,71 @@ impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for StripForeignObject<
_ => {}
}
- // Strip fallback groups when native text exists.
- match &event {
- Event::Start(e) if e.name().as_ref() == b"g" && self.fallback_depth == 0 => {
- if self.has_native_text {
- if let Ok(Some(attr)) = e.try_get_attribute("data-merman-foreignobject") {
- if attr.value.as_ref() == b"fallback" {
- self.fallback_depth = 1;
- continue;
- }
- }
- }
- }
- Event::Start(_) if self.fallback_depth > 0 => {
- self.fallback_depth += 1;
- continue;
- }
- Event::End(_) if self.fallback_depth > 0 => {
- self.fallback_depth -= 1;
- continue;
- }
- _ if self.fallback_depth > 0 => {
+ if self.fallback_depth > 0 {
+ self.buffer_fallback_event(event);
+ continue;
+ }
+
+ // Start buffering a fallback group so we can decide whether it is a
+ // duplicate of a native label once we have seen its text.
+ if let Event::Start(e) = &event {
+ if e.name().as_ref() == b"g" && is_fallback_group(e) {
+ self.fallback_depth = 1;
+ self.buffered_text.clear();
+ self.buffer.push(event);
continue;
}
- _ => {}
}
- // Track whether the diagram has native <text> elements.
- if !self.has_native_text {
- match &event {
- Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"text" => {
- if e.try_get_attribute("class").ok().flatten().is_some() {
- self.has_native_text = true;
- }
- }
- _ => {}
+ return Some(Ok(event));
+ }
+ }
+}
+
+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::Text(t) => {
+ if let Ok(decoded) = t.decode() {
+ self.buffered_text.push_str(&decoded);
}
}
+ _ => {}
+ }
+ self.buffer.push(event);
- return Some(Ok(event));
+ if self.fallback_depth == 0 {
+ let is_duplicate = self
+ .native_text_contents
+ .contains(self.buffered_text.trim());
+ let group = std::mem::take(&mut self.buffer);
+ if !is_duplicate {
+ self.output.extend(group);
+ }
}
}
}
+fn is_fallback_group(e: &quick_xml::events::BytesStart<'_>) -> bool {
+ e.try_get_attribute("data-merman-foreignobject")
+ .ok()
+ .flatten()
+ .is_some_and(|attr| attr.value.as_ref() == b"fallback")
+}
+
pub(super) fn process<'a>(
inner: impl Iterator<Item = Result<Event<'a>>>,
+ svg: &str,
) -> impl Iterator<Item = Result<Event<'a>>> {
StripForeignObject {
inner,
foreign_depth: 0,
+ native_text_contents: collect_native_text_contents(svg),
+ buffer: Vec::new(),
fallback_depth: 0,
- has_native_text: false,
+ buffered_text: String::new(),
+ output: VecDeque::new(),
}
}
diff --git a/crates/mermaid_render/src/postprocess/strip_invalid_css.rs b/crates/mermaid_render/src/postprocess/strip_invalid_css.rs
deleted file mode 100644
index 12efb99be2e..00000000000
--- a/crates/mermaid_render/src/postprocess/strip_invalid_css.rs
+++ /dev/null
@@ -1,161 +0,0 @@
-//! Removes CSS constructs that `usvg`/`resvg` cannot handle.
-//!
-//! - `@keyframes` and `@-webkit-keyframes` blocks
-//! - `:root { ... }` blocks (CSS custom properties)
-//! - `:not(...)` pseudo-selectors
-//! - `deg` angle units (e.g. `rotate(45deg)` → `rotate(45)`)
-//!
-//! Also removes `!important` declarations (so that our injected theme CSS
-//! always wins).
-
-use std::borrow::Cow;
-
-use anyhow::Result;
-use quick_xml::events::{BytesText, Event};
-
-struct StripInvalidCss<I> {
- inner: I,
- in_style: bool,
-}
-
-impl<'a, I: Iterator<Item = Result<Event<'a>>>> Iterator for StripInvalidCss<I> {
- type Item = Result<Event<'a>>;
-
- fn next(&mut self) -> Option<Self::Item> {
- let event = match self.inner.next()? {
- Ok(ev) => ev,
- Err(e) => return Some(Err(e)),
- };
-
- match &event {
- Event::Start(e) if e.name().as_ref() == b"style" => {
- self.in_style = true;
- }
- Event::End(e) if e.name().as_ref() == b"style" => {
- self.in_style = false;
- }
- Event::Text(text) if self.in_style => {
- let css_text = match std::str::from_utf8(text.as_ref()) {
- Ok(s) => s,
- Err(e) => return Some(Err(e.into())),
- };
- return Some(match strip_unsupported_css(css_text) {
- Cow::Borrowed(_) => Ok(event),
- Cow::Owned(processed) => Ok(Event::Text(BytesText::from_escaped(processed))),
- });
- }
- _ => {}
- }
-
- Some(Ok(event))
- }
-}
-
-pub(super) fn process<'a>(
- events: impl Iterator<Item = Result<Event<'a>>>,
-) -> impl Iterator<Item = Result<Event<'a>>> {
- StripInvalidCss {
- inner: events,
- in_style: false,
- }
-}
-
-fn strip_unsupported_css(css: &str) -> Cow<'_, str> {
- let mut chars = css.char_indices().peekable();
- let mut result = None;
- let mut copied_until = 0;
-
- while let Some((i, _)) = chars.next() {
- let remaining = &css[i..];
-
- if remaining.starts_with("@keyframes")
- || remaining.starts_with("@-webkit-keyframes")
- || remaining.starts_with(":root")
- {
- let result = result.get_or_insert_with(|| String::with_capacity(css.len()));
- result.push_str(&css[copied_until..i]);
- skip_css_block(&mut chars);
- copied_until = chars.peek().map_or(css.len(), |&(i, _)| i);
- }
- }
-
- let mut result = if let Some(mut result) = result {
- result.push_str(&css[copied_until..]);
- Cow::Owned(result)
- } else {
- Cow::Borrowed(css)
- };
-
- strip_css_angle_units(&mut result);
- strip_css_important(&mut result);
- result
-}
-
-fn skip_css_block(chars: &mut std::iter::Peekable<std::str::CharIndices>) {
- for (_, c) in chars.by_ref() {
- if c == '{' {
- break;
- }
- }
- let mut depth = 1u32;
- for (_, c) in chars.by_ref() {
- match c {
- '{' => depth += 1,
- '}' => {
- depth -= 1;
- if depth == 0 {
- return;
- }
- }
- _ => {}
- }
- }
-}
-
-fn replace_all_in_place(css: &mut Cow<'_, str>, needle: &str, replacement: &str) {
- while let Some(pos) = css.as_ref().find(needle) {
- css.to_mut()
- .replace_range(pos..pos + needle.len(), replacement);
- }
-}
-
-fn strip_css_angle_units(css: &mut Cow<'_, str>) {
- replace_all_in_place(css, "deg)", ")");
-}
-
-/// Strip `!important` from mermaid's generated CSS so that our injected
-/// theme CSS (which uses `!important`) always takes priority. This works
-/// around a usvg cascade bug where competing `!important` rules are
-/// resolved by first-wins rather than the CSS spec's last-wins.
-fn strip_css_important(css: &mut Cow<'_, str>) {
- replace_all_in_place(css, "!important", "");
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn strips_keyframes() {
- let input = "@keyframes bounce { 0% { transform: scale(1); } 100% { transform: scale(1.1); } } .node rect { fill: red; }";
- let result = strip_unsupported_css(input);
- assert!(!result.contains("@keyframes"), "got: {result}");
- assert!(result.contains(".node rect"), "got: {result}");
- }
-
- #[test]
- fn strips_root_blocks() {
- let input = ":root { --bg: white; } .foo { color: red; }";
- let result = strip_unsupported_css(input);
- assert!(!result.contains(":root"), "got: {result}");
- assert!(result.contains(".foo"), "got: {result}");
- }
-
- #[test]
- fn strips_deg_units() {
- let input = ".foo { transform: rotate(45deg); }";
- let result = strip_unsupported_css(input);
- assert!(result.contains("rotate(45)"), "got: {result}");
- assert!(!result.contains("deg"), "got: {result}");
- }
-}
diff --git a/crates/mermaid_render/src/render.rs b/crates/mermaid_render/src/render.rs
index 22c49d3f35f..086f4efa62d 100644
--- a/crates/mermaid_render/src/render.rs
+++ b/crates/mermaid_render/src/render.rs
@@ -14,9 +14,16 @@ pub(super) fn render_mermaid(source: &str, theme: &MermaidTheme) -> Result<Strin
.with_site_config(config)
.with_vendored_text_measurer()
.with_diagram_id(&diagram_id);
+ // Apply merman's raster-safe pipeline before Zed-specific styling. The
+ // pipeline handles generic rasterizer compatibility cleanup: foreignObject
+ // fallback text, unsupported CSS removal, and invalid SVG attribute cleanup.
+ // Zed also strips merman's existing `!important` declarations before
+ // injecting its own theme CSS so host styling wins consistently in usvg/resvg.
+ let pipeline = merman::render::SvgPipeline::resvg_safe()
+ .with_postprocessor(merman::render::CssOverridePostprocessor::strip_existing_important());
let svg = renderer
- .render_svg_sync(source)
+ .render_svg_with_pipeline_sync(source, &pipeline)
.context("merman render failed")?
.ok_or_else(|| anyhow!("merman returned no SVG for the given input"))?;
@@ -120,3 +127,39 @@ fn to_merman_config(theme: &MermaidTheme) -> merman::MermaidConfig {
"themeVariables": theme_vars,
}))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn render_stage_applies_resvg_safe_pipeline() {
+ let html_label_source =
+ "classDiagram\n class Shelter {\n -List~Animal~ animals\n }";
+ let html_label_svg =
+ render_mermaid(html_label_source, &MermaidTheme::default()).expect("render failed");
+
+ assert!(
+ !html_label_svg.contains("<foreignObject"),
+ "got: {html_label_svg}"
+ );
+ assert!(
+ html_label_svg.contains(r#"data-merman-foreignobject="fallback""#),
+ "got: {html_label_svg}"
+ );
+ assert!(
+ !html_label_svg.contains("&amp;lt;"),
+ "got: {html_label_svg}"
+ );
+
+ let css_source = "sequenceDiagram\n Alice->>Bob: Hello\n Bob-->>Alice: Hi";
+ let css_svg = render_mermaid(css_source, &MermaidTheme::default()).expect("render failed");
+
+ assert!(!css_svg.contains("@keyframes"), "got: {css_svg}");
+ assert!(!css_svg.contains("@-webkit-keyframes"), "got: {css_svg}");
+ assert!(!css_svg.contains(":root"), "got: {css_svg}");
+ assert!(!css_svg.contains("animation:"), "got: {css_svg}");
+ assert!(!css_svg.contains("animation-name:"), "got: {css_svg}");
+ assert!(!css_svg.contains("!important"), "got: {css_svg}");
+ }
+}