Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
markdown: Mermaid zoom (#62115)
Cameron Mcloughlin00cba838ad4e
diff --git a/Cargo.lock b/Cargo.lockindex 45930038d43..7f961e39f4d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7897,6 +7897,7 @@ dependencies = ["sum_tree","taffy","thiserror 2.0.17",+ "tracing","ttf-parser","unicode-segmentation","url",@@ -7909,6 +7910,7 @@ dependencies = ["windows 0.61.3","zed-font-kit","zed-scap",+ "ztracing",][[package]]@@ -11069,7 +11071,9 @@ dependencies = ["merman","quick-xml 0.38.3","serde_json",+ "tracing","usvg",+ "ztracing",][[package]]diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 4e0af6adee3..145019d7dd4 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -11442,6 +11442,7 @@ impl ThreadView {style: MarkdownStyle,cx: &App,) -> MarkdownElement {+ let list_state = self.list_state.clone();render_agent_markdown(markdown,style,@@ -11449,6 +11450,12 @@ impl ThreadView {&self.code_span_resolver,cx,)+ // Zooming a diagram grows/shrinks its block; pause tail-following so the+ // viewport stays put instead of snapping back to the bottom. The list+ // resumes following on its own once the content returns to the bottom.+ .on_mermaid_zoom(move |_window, _cx| {+ list_state.pause_following_tail();+ })}fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.tomlindex e8d1b657d05..de7e1b57720 100644--- a/crates/gpui/Cargo.toml+++ b/crates/gpui/Cargo.toml@@ -93,6 +93,7 @@ strum.workspace = truesum_tree.workspace = truetaffy = "=0.12.2"thiserror.workspace = true+tracing.workspace = truegpui_util.workspace = truehdrhistogram = { workspace = true, optional = true }waker-fn = "1.2.0"@@ -104,6 +105,7 @@ url.workspace = trueuuid.workspace = trueweb-time.workspace = trueheapless.workspace = true+ztracing.workspace = true[target.'cfg(target_family = "wasm")'.dependencies]getrandom = { version = "0.3.4", features = ["wasm_js"] }@@ -170,10 +172,8 @@ embed-resource = { version = "3.0", optional = true }bindgen = "0.71"cbindgen.workspace = true----+[package.metadata.cargo-machete]+ignored = ["tracing"][[example]]name = "hello_world"diff --git a/crates/gpui/src/elements/list.rs b/crates/gpui/src/elements/list.rsindex 77d33ca2489..fa21d107062 100644--- a/crates/gpui/src/elements/list.rs+++ b/crates/gpui/src/elements/list.rs@@ -634,6 +634,19 @@ impl ListState {}}+ /// Pause tail-following, freezing the list at its current scroll+ /// position. Unlike [`Self::set_follow_mode`] with [`FollowMode::Normal`],+ /// this keeps the list in `Tail` mode, so it will resume following+ /// automatically once the view returns to the bottom. No-op when the list+ /// isn't currently following.+ ///+ /// Useful when something other than the user grows an item (e.g. zooming a+ /// diagram) and the current position should stay put rather than snapping+ /// to the end.+ pub fn pause_following_tail(&self) {+ self.0.borrow_mut().follow_state.stop_following();+ }+/// Returns whether the list is currently actively following the/// tail (snapping to the end on each layout).pub fn is_following_tail(&self) -> bool {@@ -1574,12 +1587,12 @@ impl Element for List {cx: &mut App,) {let current_view = window.current_view();- window.with_content_mask(Some(ContentMask { bounds }), |window| {- for item in &mut prepaint.layout.item_layouts {- item.element.paint(window, cx);- }- });+ // Register the scroll listener before painting children so that, in+ // the bubble phase (which runs in reverse registration order),+ // children's scroll-wheel handlers run first and can stop propagation+ // to prevent the list from scrolling. This matches the ordering of+ // div-based scroll containers.let list_state = self.state.clone();let height = bounds.size.height;let scroll_top = prepaint.layout.scroll_top;@@ -1599,6 +1612,12 @@ impl Element for List {)}});++ window.with_content_mask(Some(ContentMask { bounds }), |window| {+ for item in &mut prepaint.layout.item_layouts {+ item.element.paint(window, cx);+ }+ });}}@@ -1705,8 +1724,9 @@ mod test {use std::rc::Rc;use crate::{- self as gpui, AppContext, Bounds, Context, Element, FollowMode, IntoElement, ListState,- Render, Styled, TestAppContext, Window, canvas, div, list, point, px, size,+ self as gpui, AppContext, Bounds, Context, Element, FollowMode, InteractiveElement,+ IntoElement, ListState, Render, Styled, TestAppContext, Window, canvas, div, list, point,+ px, size,};#[gpui::test]@@ -1850,6 +1870,60 @@ mod test {assert_eq!(offset.offset_in_item, px(0.));}+ #[gpui::test]+ fn test_child_scroll_handler_can_stop_list_scroll(cx: &mut TestAppContext) {+ let cx = cx.add_empty_window();++ let state = ListState::new(5, crate::ListAlignment::Top, px(10.));+ let child_saw_event = Rc::new(Cell::new(false));++ struct TestView {+ state: ListState,+ child_saw_event: Rc<Cell<bool>>,+ }+ impl Render for TestView {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let child_saw_event = self.child_saw_event.clone();+ list(self.state.clone(), move |_, _, _| {+ let child_saw_event = child_saw_event.clone();+ div()+ .h(px(20.))+ .w_full()+ .on_scroll_wheel(move |_, _, cx| {+ child_saw_event.set(true);+ cx.stop_propagation();+ })+ .into_any()+ })+ .w_full()+ .h_full()+ }+ }++ cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {+ cx.new(|_| TestView {+ state: state.clone(),+ child_saw_event: child_saw_event.clone(),+ })+ .into_any_element()+ });++ cx.simulate_event(ScrollWheelEvent {+ position: point(px(50.), px(10.)),+ delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),+ ..Default::default()+ });++ assert!(+ child_saw_event.get(),+ "the child's scroll-wheel handler should run"+ );+ // The child stopped propagation, so the list must not have scrolled.+ let offset = state.logical_scroll_top();+ assert_eq!(offset.item_ix, 0);+ assert_eq!(offset.offset_in_item, px(0.));+ }+struct TestListView(ListState);impl Render for TestListView {fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {@@ -2331,6 +2405,116 @@ mod test {assert!(state.is_following_tail());}+ #[gpui::test]+ fn test_pause_following_tail_reengages_when_still_at_bottom(cx: &mut TestAppContext) {+ let cx = cx.add_empty_window();++ // 10 items × 50px = 500px total, 200px viewport.+ let state = ListState::new(10, crate::ListAlignment::Top, px(0.));++ struct TestView(ListState);+ impl Render for TestView {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ list(self.0.clone(), |_, _, _| {+ div().h(px(50.)).w_full().into_any()+ })+ .w_full()+ .h_full()+ }+ }++ let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));+ state.set_follow_mode(FollowMode::Tail);++ cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {+ view.clone().into_any_element()+ });+ assert!(state.is_following_tail());++ // Pausing while the view is still at the bottom (e.g. a no-op zoom)+ // must not strand follow-tail: the next layout has to re-engage so the+ // invariant "at the bottom + new content => visible" is preserved.+ state.pause_following_tail();+ assert!(!state.is_following_tail());++ cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {+ view.into_any_element()+ });+ assert!(+ state.is_following_tail(),+ "pausing while at the bottom must re-engage follow-tail on the next layout"+ );+ }++ #[gpui::test]+ fn test_pause_following_tail_freezes_off_bottom(cx: &mut TestAppContext) {+ let cx = cx.add_empty_window();++ // 10 items, 200px viewport. Item height is adjustable to simulate a+ // diagram block growing/shrinking on zoom.+ let item_height = Rc::new(Cell::new(50usize));+ let state = ListState::new(10, crate::ListAlignment::Top, px(0.));++ struct TestView {+ state: ListState,+ item_height: Rc<Cell<usize>>,+ }+ impl Render for TestView {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let height = self.item_height.get();+ list(self.state.clone(), move |_, _, _| {+ div().h(px(height as f32)).w_full().into_any()+ })+ .w_full()+ .h_full()+ }+ }++ let view = cx.update(|_, cx| {+ cx.new(|_| TestView {+ state: state.clone(),+ item_height: item_height.clone(),+ })+ });+ state.set_follow_mode(FollowMode::Tail);++ // At the bottom: 500px content, 200px viewport → top at item 6.+ cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {+ view.clone().into_any_element()+ });+ assert_eq!(state.logical_scroll_top().item_ix, 6);+ assert!(state.is_following_tail());++ // Pause, then grow items (a zoom-in that pushes content below the fold).+ // The frozen top must stay put rather than snapping to the new end, and+ // following stays paused since we're no longer at the bottom.+ state.pause_following_tail();+ item_height.set(80);+ state.remeasure();+ cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {+ view.clone().into_any_element()+ });+ let offset = state.logical_scroll_top();+ assert_eq!(offset.item_ix, 6);+ assert_eq!(offset.offset_in_item, px(0.));+ assert!(+ !state.is_following_tail(),+ "a paused list must not re-engage while the frozen top is off the bottom"+ );++ // Shrink back (zoom-out) so the frozen top once again reaches the+ // bottom: follow-tail must re-engage on its own.+ item_height.set(50);+ state.remeasure();+ cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {+ view.into_any_element()+ });+ assert!(+ state.is_following_tail(),+ "returning to the bottom must restore follow-tail"+ );+ }+#[gpui::test]fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {let cx = cx.add_empty_window();diff --git a/crates/gpui/src/svg_renderer.rs b/crates/gpui/src/svg_renderer.rsindex 35124b15ef8..d42942b3fba 100644--- a/crates/gpui/src/svg_renderer.rs+++ b/crates/gpui/src/svg_renderer.rs@@ -94,6 +94,14 @@ pub struct SvgRenderer {usvg_options: Arc<usvg::Options<'static>>,}+/// A parsed SVG document that can be rasterized at any scale.+///+/// Produced by [`SvgRenderer::parse_svg`] and rasterized by+/// [`SvgRenderer::render_parsed`]. Parsing resolves fonts and converts text+/// to paths, so callers that need to rasterize the same SVG at multiple+/// scales should retain this value to avoid re-paying the parse cost.+pub struct ParsedSvg(usvg::Tree);+/// The size in which to render the SVG.pub enum SvgSize {/// An absolute size in device pixels.@@ -169,29 +177,46 @@ impl SvgRenderer {}}+ /// Parses SVG data into a [`ParsedSvg`] that can be rasterized at any scale.+ #[ztracing::instrument(skip_all)]+ pub fn parse_svg(&self, bytes: &[u8]) -> Result<ParsedSvg, usvg::Error> {+ usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg)+ }++ /// Rasterizes a previously parsed SVG into an image buffer.+ ///+ /// `scale_factor` is multiplied by [`SMOOTH_SVG_SCALE_FACTOR`], matching+ /// [`SvgRenderer::render_single_frame`].+ #[ztracing::instrument(skip_all)]+ pub fn render_parsed(+ &self,+ svg: &ParsedSvg,+ scale_factor: f32,+ ) -> Result<Arc<RenderImage>, usvg::Error> {+ let pixmap = rasterize_tree(+ &svg.0,+ SvgSize::ScaleFactor(scale_factor * SMOOTH_SVG_SCALE_FACTOR),+ )?;+ let mut buffer =+ image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take()).unwrap();++ for pixel in buffer.chunks_exact_mut(4) {+ swap_rgba_pa_to_bgra(pixel);+ }++ let mut image = RenderImage::new(SmallVec::from_const([Frame::new(buffer)]));+ image.scale_factor = SMOOTH_SVG_SCALE_FACTOR;+ Ok(Arc::new(image))+ }+/// Renders the given bytes into an image buffer.pub fn render_single_frame(&self,bytes: &[u8],scale_factor: f32,) -> Result<Arc<RenderImage>, usvg::Error> {- self.render_pixmap(- bytes,- SvgSize::ScaleFactor(scale_factor * SMOOTH_SVG_SCALE_FACTOR),- )- .map(|pixmap| {- let mut buffer =- image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())- .unwrap();-- for pixel in buffer.chunks_exact_mut(4) {- swap_rgba_pa_to_bgra(pixel);- }-- let mut image = RenderImage::new(SmallVec::from_const([Frame::new(buffer)]));- image.scale_factor = SMOOTH_SVG_SCALE_FACTOR;- Arc::new(image)- })+ let svg = self.parse_svg(bytes)?;+ self.render_parsed(&svg, scale_factor)}pub(crate) fn render_alpha_mask(@@ -228,43 +253,45 @@ impl SvgRenderer {}fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {- // Cap the size of the rendered pixmap to avoid texture allocation panics- // Related issue: #56466- const MAX_SIZE: f32 = 8192.0;-let tree = usvg::Tree::from_data(bytes, &self.usvg_options)?;- let svg_size = tree.size();- let mut scale = match size {- SvgSize::Size(size) => size.width.0 as f32 / svg_size.width(),- SvgSize::ScaleFactor(scale) => scale,- };+ rasterize_tree(&tree, size)+ }+}- let width = svg_size.width() * scale;- if width > MAX_SIZE {- log::warn!("Attempted to render pixmap where width ({width}) > MAX_SIZE ({MAX_SIZE})");- scale *= MAX_SIZE / width;- }- let height = svg_size.height() * scale;- if height > MAX_SIZE {- log::warn!(- "Attempted to render pixmap where height ({height}) > MAX_SIZE ({MAX_SIZE})"- );- scale *= MAX_SIZE / height;- }+fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result<Pixmap, usvg::Error> {+ // Cap the size of the rendered pixmap to avoid texture allocation panics+ // Related issue: #56466+ const MAX_SIZE: f32 = 8192.0;++ let svg_size = tree.size();+ let mut scale = match size {+ SvgSize::Size(size) => size.width.0 as f32 / svg_size.width(),+ SvgSize::ScaleFactor(scale) => scale,+ };++ let width = svg_size.width() * scale;+ if width > MAX_SIZE {+ log::warn!("Attempted to render pixmap where width ({width}) > MAX_SIZE ({MAX_SIZE})");+ scale *= MAX_SIZE / width;+ }+ let height = svg_size.height() * scale;+ if height > MAX_SIZE {+ log::warn!("Attempted to render pixmap where height ({height}) > MAX_SIZE ({MAX_SIZE})");+ scale *= MAX_SIZE / height;+ }- // Render the SVG to a pixmap with the specified width and height.- let mut pixmap = resvg::tiny_skia::Pixmap::new(- (svg_size.width() * scale) as u32,- (svg_size.height() * scale) as u32,- )- .ok_or(usvg::Error::InvalidSize)?;+ // Render the SVG to a pixmap with the specified width and height.+ let mut pixmap = resvg::tiny_skia::Pixmap::new(+ (svg_size.width() * scale) as u32,+ (svg_size.height() * scale) as u32,+ )+ .ok_or(usvg::Error::InvalidSize)?;- let transform = resvg::tiny_skia::Transform::from_scale(scale, scale);+ let transform = resvg::tiny_skia::Transform::from_scale(scale, scale);- resvg::render(&tree, transform, &mut pixmap.as_mut());+ resvg::render(tree, transform, &mut pixmap.as_mut());- Ok(pixmap)- }+ Ok(pixmap)}fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) {diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rsindex 06581ca3066..f9a8c0dd509 100644--- a/crates/markdown/src/markdown.rs+++ b/crates/markdown/src/markdown.rs@@ -54,6 +54,12 @@ use util::ResultExt;use crate::parser::CodeBlockKind;+const MERMAID_MAX_ZOOM: f32 = 2.0;+/// Zoom levels within this distance of 1.0 snap back to exactly 1.0 so users+/// can easily return to the default size.+const MERMAID_ZOOM_SNAP_TOLERANCE: f32 = 0.05;+const MERMAID_ZOOM_DEBOUNCE: Duration = Duration::from_millis(300);+/// A callback function that can be used to customize the style of links based on the destination URL./// If the callback returns `None`, the default link style will be used.type LinkStyleCallback = Rc<dyn Fn(&str, &App) -> Option<TextStyleRefinement>>;@@ -61,6 +67,9 @@ pub type CodeSpanLinkCallback = Arc<dyn Fn(&str, &App) -> Option<SharedString> +type UrlHoverCallback = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;type SourceClickCallback = Box<dyn Fn(usize, usize, &mut Window, &mut App) -> bool>;type CheckboxToggleCallback = Rc<dyn Fn(Range<usize>, bool, &mut Window, &mut App)>;+/// Invoked when a mermaid diagram's zoom level changes (via scroll gesture or+/// the reset button), so a scroll container can keep the diagram anchored.+pub type MermaidZoomCallback = Rc<dyn Fn(&mut Window, &mut App)>;#[derive(Clone, Copy, Default)]pub struct BlockQuoteKindColors {@@ -389,6 +398,53 @@ impl MarkdownStyle {}}+/// Per-diagram view state, keyed by source offset in [`Markdown::mermaid_views`].+struct MermaidViewState {+ /// Whether the source code is shown instead of the rendered diagram.+ showing_code: bool,+ /// The display scale relative to the diagram's natural size; 1.0 is 1:1.+ zoom: f32,+ /// Whether the user zoomed out to the fit-to-width floor. While set, the+ /// zoom tracks the container width so the diagram stays fully visible+ /// when the container is resized, instead of keeping a stale absolute+ /// zoom computed against the old width.+ zoomed_to_fit: bool,+ /// Horizontal scroll position, used when the diagram overflows.+ scroll_handle: ScrollHandle,+ /// The pending debounced re-raster scheduled by the last zoom change.+ debounce_task: Option<Task<()>>,+ /// Overrides the scroll container width, which tests can't obtain from+ /// the scroll handle since its bounds are only set during layout.+ #[cfg(test)]+ container_width_for_test: Option<Pixels>,+}++impl MermaidViewState {+ /// The width of the diagram's scroll container as of the last layout,+ /// if it has been laid out.+ fn container_width(&self) -> Option<Pixels> {+ #[cfg(test)]+ if let Some(width) = self.container_width_for_test {+ return Some(width);+ }+ Some(self.scroll_handle.bounds().size.width).filter(|width| *width > px(0.))+ }+}++impl Default for MermaidViewState {+ fn default() -> Self {+ Self {+ showing_code: false,+ zoom: 1.0,+ zoomed_to_fit: false,+ scroll_handle: ScrollHandle::new(),+ debounce_task: None,+ #[cfg(test)]+ container_width_for_test: None,+ }+ }+}+pub struct Markdown {source: SharedString,selection: Selection,@@ -408,7 +464,12 @@ pub struct Markdown {options: MarkdownOptions,mermaid_state: MermaidState,_mermaid_theme_subscription: Option<Subscription>,- mermaid_showing_code: HashSet<usize>,+ /// Per-diagram view state (current tab, zoom, scroll position, and pending+ /// debounced re-raster) keyed by source offset. Distinct from+ /// [`MermaidState`], which caches the rendered diagrams themselves keyed by+ /// contents. All entries are retained against the parsed diagrams on each+ /// reparse, so a single map keeps that bookkeeping in one place.+ mermaid_views: HashMap<usize, MermaidViewState>,copied_code_blocks: HashSet<ElementId>,wrapped_code_blocks: HashSet<usize>,code_block_scroll_handles: BTreeMap<usize, ScrollHandle>,@@ -603,7 +664,7 @@ impl Markdown {options,mermaid_state: MermaidState::default(),_mermaid_theme_subscription: theme_subscription,- mermaid_showing_code: HashSet::default(),+ mermaid_views: HashMap::default(),copied_code_blocks: HashSet::default(),wrapped_code_blocks: HashSet::default(),code_block_scroll_handles: BTreeMap::default(),@@ -660,19 +721,159 @@ impl Markdown {return;}- self.mermaid_state.clear();- self.mermaid_state.update(&self.parsed_markdown, cx);+ self.mermaid_state.clear(cx);+ let mermaid_views = &self.mermaid_views;+ self.mermaid_state.update(+ &self.parsed_markdown,+ |source_offset| {+ mermaid_views+ .get(&source_offset)+ .map_or(1.0, |view| view.zoom)+ },+ cx,+ );cx.notify();}pub(crate) fn is_mermaid_showing_code(&self, source_offset: usize) -> bool {- self.mermaid_showing_code.contains(&source_offset)+ self.mermaid_views+ .get(&source_offset)+ .is_some_and(|view| view.showing_code)}pub(crate) fn toggle_mermaid_tab(&mut self, source_offset: usize) {- if !self.mermaid_showing_code.remove(&source_offset) {- self.mermaid_showing_code.insert(source_offset);+ let view = self.mermaid_views.entry(source_offset).or_default();+ view.showing_code = !view.showing_code;+ }++ pub(crate) fn mermaid_zoom_level(&self, source_offset: usize) -> f32 {+ self.mermaid_views+ .get(&source_offset)+ .map_or(1.0, |view| view.zoom)+ }++ /// The smallest zoom level for a diagram: the scale that makes it span+ /// the content width, capped at 1.0 so diagrams that already fit are+ /// never zoomed out below their natural size. Falls back to 1.0 when the+ /// diagram has no raster yet or the container hasn't been laid out.+ fn mermaid_min_zoom_level(&self, source_offset: usize) -> f32 {+ let Some(diagram) = self.parsed_markdown.mermaid_diagrams.get(&source_offset) else {+ return 1.0;+ };+ let Some(natural_size) = self.mermaid_state.natural_size(&diagram.contents) else {+ return 1.0;+ };+ let Some(container_width) = self+ .mermaid_views+ .get(&source_offset)+ .and_then(|view| view.container_width())+ else {+ return 1.0;+ };+ if natural_size.width <= container_width {+ return 1.0;+ }+ container_width / natural_size.width+ }++ pub(crate) fn set_mermaid_zoom_level(+ &mut self,+ source_offset: usize,+ zoom: f32,+ cx: &mut Context<Self>,+ ) {+ let min_zoom = self.mermaid_min_zoom_level(source_offset);+ let requested_zoom = zoom;+ let mut zoom = zoom.clamp(min_zoom, MERMAID_MAX_ZOOM);+ if (zoom - 1.0).abs() <= MERMAID_ZOOM_SNAP_TOLERANCE {+ zoom = 1.0;}+ // The user zoomed out to (or past) the fit-to-width floor. From here+ // on the zoom tracks the container width (see+ // `effective_mermaid_zoom_level`), until the user zooms back in. A+ // zoom landing exactly at 1.0 only sticks when it was clamped, so+ // resetting to the natural size never turns tracking on.+ let zoomed_to_fit = requested_zoom < min_zoom || (zoom <= min_zoom && zoom < 1.0);++ let debounce_task = self.schedule_mermaid_rerasterize(source_offset, cx);+ let view = self.mermaid_views.entry(source_offset).or_default();+ view.zoom = zoom;+ view.zoomed_to_fit = zoomed_to_fit;+ view.debounce_task = Some(debounce_task);+ cx.notify();+ }++ /// The zoom level to display a diagram at, syncing a fit-to-width zoom+ /// with the current container width. Called at render time so that a+ /// fully zoomed-out diagram stays stuck to the container width when the+ /// container is resized, rather than keeping a stale absolute zoom.+ pub(crate) fn effective_mermaid_zoom_level(+ &mut self,+ source_offset: usize,+ cx: &mut Context<Self>,+ ) -> f32 {+ let zoom = self.mermaid_zoom_level(source_offset);+ let zoomed_to_fit = self+ .mermaid_views+ .get(&source_offset)+ .is_some_and(|view| view.zoomed_to_fit);+ if !zoomed_to_fit {+ return zoom;+ }+ let min_zoom = self.mermaid_min_zoom_level(source_offset);+ if (min_zoom - zoom).abs() < 0.001 {+ return zoom;+ }+ let debounce_task = self.schedule_mermaid_rerasterize(source_offset, cx);+ if let Some(view) = self.mermaid_views.get_mut(&source_offset) {+ view.zoom = min_zoom;+ view.debounce_task = Some(debounce_task);+ }+ min_zoom+ }++ /// Schedules a debounced re-raster of a diagram at its current zoom.+ /// Storing the returned task in `MermaidViewState::debounce_task`+ /// replaces (and thereby cancels) the previous timer, debouncing the+ /// expensive re-raster until zoom changes settle. Until then, the+ /// existing raster is displayed scaled to the new zoom.+ fn schedule_mermaid_rerasterize(+ &self,+ source_offset: usize,+ cx: &mut Context<Self>,+ ) -> Task<()> {+ cx.spawn(async move |this, cx| {+ cx.background_executor().timer(MERMAID_ZOOM_DEBOUNCE).await;+ this.update(cx, |this, cx| {+ if let Some(view) = this.mermaid_views.get_mut(&source_offset) {+ view.debounce_task = None;+ }+ this.rerasterize_mermaid_diagram(source_offset, cx);+ })+ .ok();+ })+ }++ pub(crate) fn mermaid_scroll_handle(&mut self, source_offset: usize) -> ScrollHandle {+ self.mermaid_views+ .entry(source_offset)+ .or_default()+ .scroll_handle+ .clone()+ }++ /// Re-rasterizes a single mermaid diagram at exactly the scale it is+ /// displayed at, reusing the cached parsed SVG so that neither mermaid+ /// layout nor SVG parsing is re-run. While the new raster is pending, the+ /// previous image keeps being displayed.+ fn rerasterize_mermaid_diagram(&mut self, source_offset: usize, cx: &mut Context<Self>) {+ let Some(diagram) = self.parsed_markdown.mermaid_diagrams.get(&source_offset) else {+ return;+ };+ let contents = diagram.contents.clone();+ let zoom = self.mermaid_zoom_level(source_offset);+ self.mermaid_state.rerasterize_diagram(&contents, zoom, cx);+ cx.notify();}fn clear_code_block_scroll_handles(&mut self) {@@ -977,7 +1178,7 @@ impl Markdown {};self.active_root_block = None;self.images_by_source_offset.clear();- self.mermaid_state.clear();+ self.mermaid_state.clear(cx);cx.notify();cx.refresh_windows();return;@@ -1121,12 +1322,21 @@ impl Markdown {}if this.options.render_mermaid_diagrams {let parsed_markdown = this.parsed_markdown.clone();- this.mermaid_state.update(&parsed_markdown, cx);- this.mermaid_showing_code- .retain(|offset| parsed_markdown.mermaid_diagrams.contains_key(offset));+ this.mermaid_views+ .retain(|offset, _| parsed_markdown.mermaid_diagrams.contains_key(offset));+ let mermaid_views = &this.mermaid_views;+ this.mermaid_state.update(+ &parsed_markdown,+ |source_offset| {+ mermaid_views+ .get(&source_offset)+ .map_or(1.0, |view| view.zoom)+ },+ cx,+ );} else {- this.mermaid_state.clear();- this.mermaid_showing_code.clear();+ this.mermaid_state.clear(cx);+ this.mermaid_views.clear();}this.pending_parse.take();if this.should_reparse {@@ -1300,9 +1510,15 @@ pub struct MarkdownElement {code_span_link: Option<CodeSpanLinkCallback>,on_source_click: Option<SourceClickCallback>,on_checkbox_toggle: Option<CheckboxToggleCallback>,+ on_mermaid_zoom: Option<MermaidZoomCallback>,image_resolver: Option<Box<dyn Fn(&str) -> Option<ImageSource>>>,show_root_block_markers: bool,autoscroll: AutoscrollBehavior,+ /// Test-only hook to observe the laid-out text when this element is+ /// rendered beneath a view, where the layout state isn't otherwise+ /// reachable.+ #[cfg(test)]+ on_render: Option<Box<dyn Fn(RenderedText)>>,}impl MarkdownElement {@@ -1320,9 +1536,12 @@ impl MarkdownElement {code_span_link: None,on_source_click: None,on_checkbox_toggle: None,+ on_mermaid_zoom: None,image_resolver: None,show_root_block_markers: false,autoscroll: AutoscrollBehavior::Propagate,+ #[cfg(test)]+ on_render: None,}}@@ -1352,6 +1571,14 @@ impl MarkdownElement {self}+ /// Registers a test-only callback invoked with the laid-out text each+ /// time this element runs layout.+ #[cfg(test)]+ pub(crate) fn on_render(mut self, callback: impl Fn(RenderedText) + 'static) -> Self {+ self.on_render = Some(Box::new(callback));+ self+ }+pub fn on_url_click(mut self,handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,@@ -1392,6 +1619,14 @@ impl MarkdownElement {self}+ /// Registers a callback invoked when a mermaid diagram's zoom level changes.+ /// Consumers that scroll the markdown can use this to keep the diagram's+ /// position anchored while it grows or shrinks.+ pub fn on_mermaid_zoom(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {+ self.on_mermaid_zoom = Some(Rc::new(handler));+ self+ }+pub fn image_resolver(mut self,resolver: impl Fn(&str) -> Option<ImageSource> + 'static,@@ -2316,8 +2551,13 @@ impl Element for MarkdownElement {&& let Some(mermaid_diagram) =parsed_markdown.mermaid_diagrams.get(&range.start){- let showing_code =- self.markdown.read(cx).is_mermaid_showing_code(range.start);+ let (showing_code, zoom) =+ self.markdown.update(cx, |markdown, cx| {+ (+ markdown.is_mermaid_showing_code(range.start),+ markdown.effective_mermaid_zoom_level(range.start, cx),+ )+ });let copy_button_visibility = match &self.code_block_renderer {CodeBlockRenderer::Default {copy_button_visibility,@@ -2334,7 +2574,11 @@ impl Element for MarkdownElement {self.markdown.clone(),range.start,showing_code,+ zoom,copy_button_visibility,+ self.on_mermaid_zoom.clone(),+ window,+ cx,),);rendered_mermaid_block = true;@@ -2867,6 +3111,10 @@ impl Element for MarkdownElement {.update(cx, |markdown, _| markdown.clear_code_block_scroll_handles());}let mut rendered_markdown = builder.build();+ #[cfg(test)]+ if let Some(on_render) = self.on_render.as_ref() {+ on_render(rendered_markdown.text.clone());+ }let child_layout_id = rendered_markdown.element.request_layout(window, cx);let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);(layout_id, rendered_markdown)diff --git a/crates/markdown/src/mermaid.rs b/crates/markdown/src/mermaid.rsindex ae42ad453d6..32dccf67ce8 100644--- a/crates/markdown/src/mermaid.rs+++ b/crates/markdown/src/mermaid.rs@@ -1,23 +1,30 @@use collections::HashMap;use gpui::{- Animation, AnimationExt, AnyElement, ClipboardItem, Context, Entity, ImageSource, RenderImage,- StyledText, Task, img, pulsating_between,+ Animation, AnimationExt, AnyElement, App, ClipboardItem, Context, Entity, ImageSource,+ ParsedSvg, RenderImage, SMOOTH_SVG_SCALE_FACTOR, ScrollDelta, ScrollHandle, ScrollWheelEvent,+ Size, Stateful, StyledText, Task, Window, img, pulsating_between, size,};use std::collections::BTreeMap;use std::ops::Range;use std::path::Path;use std::sync::{Arc, OnceLock};use std::time::Duration;-use ui::{CopyButton, TintColor, prelude::*};+use ui::{CopyButton, ScrollAxes, Scrollbars, TintColor, Tooltip, WithScrollbar, prelude::*};use crate::parser::{CodeBlockKind, MarkdownEvent, MarkdownTag};use settings::Settings as _;use theme_settings::ThemeSettings;-use super::{CopyButtonVisibility, Markdown, MarkdownStyle, ParsedMarkdown};+use super::{CopyButtonVisibility, Markdown, MarkdownStyle, MermaidZoomCallback, ParsedMarkdown};type MermaidDiagramCache = HashMap<ParsedMarkdownMermaidDiagramContents, Arc<CachedMermaidDiagram>>;+/// Per scroll tick, zoom changes by 10 percentage points, regardless of how+/// large a delta the platform reports for the tick.+const MERMAID_ZOOM_STEP: f32 = 0.1;+/// How many pixels of precise (trackpad) scroll make up one zoom tick.+const PIXELS_PER_ZOOM_TICK: f32 = 20.0;+#[derive(Clone, Debug)]pub(crate) struct ParsedMarkdownMermaidDiagram {pub(crate) content_range: Range<usize>,@@ -38,12 +45,22 @@ pub(crate) struct MermaidState {struct CachedMermaidDiagram {render_image: Arc<OnceLock<anyhow::Result<Arc<RenderImage>>>>,- fallback_image: Option<Arc<RenderImage>>,+ parsed_svg: Arc<OnceLock<Arc<ParsedSvg>>>,+ /// The previous raster shown while `render_image` is pending, along with+ /// the scale it was rasterized at, so it can be displayed at the same+ /// logical size as the raster that will replace it.+ fallback_image: Option<(Arc<RenderImage>, f32)>,+ /// The scale, relative to the diagram's natural size, that `render_image`+ /// was (or is being) rasterized at.+ rasterized_scale: f32,_task: Task<()>,}impl MermaidState {- pub(crate) fn clear(&mut self) {+ pub(crate) fn clear(&mut self, cx: &mut App) {+ for cached in self.cache.values() {+ cached.drop_images(cx);+ }self.cache.clear();self.order.clear();}@@ -53,7 +70,7 @@ impl MermaidState {old_order: &[ParsedMarkdownMermaidDiagramContents],new_order_len: usize,cache: &MermaidDiagramCache,- ) -> Option<Arc<RenderImage>> {+ ) -> Option<(Arc<RenderImage>, f32)> {if old_order.len() != new_order_len {return None;}@@ -64,83 +81,258 @@ impl MermaidState {.render_image.get().and_then(|result| result.as_ref().ok().cloned())+ .map(|image| (image, old_cached.rasterized_scale)).or_else(|| old_cached.fallback_image.clone())})})}- pub(crate) fn update(&mut self, parsed: &ParsedMarkdown, cx: &mut Context<Markdown>) {+ pub(crate) fn update(+ &mut self,+ parsed: &ParsedMarkdown,+ zoom_for_offset: impl Fn(usize) -> f32,+ cx: &mut Context<Markdown>,+ ) {let mut new_order = Vec::new();- for mermaid_diagram in parsed.mermaid_diagrams.values() {+ let mut source_offsets = Vec::new();+ for (source_offset, mermaid_diagram) in parsed.mermaid_diagrams.iter() {new_order.push(mermaid_diagram.contents.clone());+ source_offsets.push(*source_offset);}for (idx, new_content) in new_order.iter().enumerate() {if !self.cache.contains_key(new_content) {let fallback =Self::get_fallback_image(idx, &self.order, new_order.len(), &self.cache);+ // The cache is keyed by contents, so duplicate diagrams share+ // one entry; if duplicates have different zooms, the zoom of+ // the first occurrence wins.+ let zoom = source_offsets+ .get(idx)+ .copied()+ .map_or(1.0, &zoom_for_offset);self.cache.insert(new_content.clone(),- Arc::new(CachedMermaidDiagram::new(new_content.clone(), fallback, cx)),+ Arc::new(CachedMermaidDiagram::new(+ new_content.clone(),+ zoom,+ fallback,+ cx,+ )),);}}let new_order_set: std::collections::HashSet<_> = new_order.iter().cloned().collect();- self.cache- .retain(|content, _| new_order_set.contains(content));+ self.cache.retain(|content, cached| {+ let keep = new_order_set.contains(content);+ if !keep {+ cached.drop_images(cx);+ }+ keep+ });self.order = new_order;}++ /// The natural (zoom 1.0) logical size of a diagram, if any raster of it+ /// is available to recover the size from.+ pub(crate) fn natural_size(+ &self,+ contents: &ParsedMarkdownMermaidDiagramContents,+ ) -> Option<Size<Pixels>> {+ let cached = self.cache.get(contents)?;+ let (image, rasterized_scale) = cached+ .render_image+ .get()+ .and_then(|result| result.as_ref().ok())+ .map(|image| (image.clone(), cached.rasterized_scale))+ .or_else(|| cached.fallback_image.clone())?;+ Some(mermaid_base_size(&image, rasterized_scale))+ }++ /// Re-rasterizes a single cached diagram at exactly the scale it is+ /// displayed at (`zoom` times its natural size), reusing the cached+ /// parsed SVG so that neither mermaid layout nor SVG parsing is re-run.+ /// No-ops if the entry is already rasterized at the target scale, or if+ /// it's still mid-render or failed to render.+ pub(crate) fn rerasterize_diagram(+ &mut self,+ contents: &ParsedMarkdownMermaidDiagramContents,+ zoom: f32,+ cx: &mut Context<Markdown>,+ ) {+ let Some(cached) = self.cache.get_mut(contents) else {+ return;+ };+ let Some(parsed_svg) = cached.parsed_svg.get().cloned() else {+ return;+ };+ let target_scale = zoom;+ if (cached.rasterized_scale - target_scale).abs() < 0.001 {+ return;+ }+ // The old render image lives on as the new entry's fallback, so it+ // must not be dropped here; the old fallback is no longer painted.+ // If the old raster is still pending, keep showing the previous+ // fallback so the diagram doesn't disappear mid-zoom.+ let new_fallback = match cached+ .render_image+ .get()+ .and_then(|result| result.as_ref().ok())+ {+ Some(image) => {+ if let Some((old_fallback, _)) = cached.fallback_image.clone() {+ cx.drop_image(old_fallback, None);+ }+ Some((image.clone(), cached.rasterized_scale))+ }+ None => cached.fallback_image.clone(),+ };+ let scale_factor = contents.scale as f32 / 100.0 * target_scale;+ *cached = Arc::new(CachedMermaidDiagram::new_from_parsed(+ parsed_svg,+ scale_factor,+ target_scale,+ new_fallback,+ cx,+ ));+ }}impl CachedMermaidDiagram {fn new(contents: ParsedMarkdownMermaidDiagramContents,- fallback_image: Option<Arc<RenderImage>>,+ zoom: f32,+ fallback_image: Option<(Arc<RenderImage>, f32)>,cx: &mut Context<Markdown>,) -> Self {let render_image = Arc::new(OnceLock::<anyhow::Result<Arc<RenderImage>>>::new());- let render_image_clone = render_image.clone();+ let parsed_svg = Arc::new(OnceLock::<Arc<ParsedSvg>>::new());let svg_renderer = cx.svg_renderer();let mermaid_theme = build_mermaid_theme(cx);- let task = cx.spawn(async move |this, cx| {- let value = cx- .background_spawn(async move {- let svg_string =- mermaid_render::render_to_svg(&contents.contents, &mermaid_theme)?;- let scale = contents.scale as f32 / 100.0;- svg_renderer- .render_single_frame(svg_string.as_bytes(), scale)- .map_err(|error| anyhow::anyhow!("{error}"))- })- .await;- let _ = render_image_clone.set(value);- this.update(cx, |_, cx| {- cx.notify();- })- .ok();+ let task = cx.spawn({+ let render_image = render_image.clone();+ let parsed_svg = parsed_svg.clone();+ let fallback_image = fallback_image.clone();+ async move |this, cx| {+ let value = cx+ .background_spawn(async move {+ let svg_string =+ mermaid_render::render_to_svg(&contents.contents, &mermaid_theme)?;+ let tree = svg_renderer+ .parse_svg(svg_string.as_bytes())+ .map_err(|error| anyhow::anyhow!("{error}"))?;+ let tree = Arc::new(tree);+ let scale = contents.scale as f32 / 100.0 * zoom;+ let image = svg_renderer+ .render_parsed(&tree, scale)+ .map_err(|error| anyhow::anyhow!("{error}"))?;+ anyhow::Ok((tree, image))+ })+ .await;+ let value = match value {+ Ok((tree, image)) => {+ parsed_svg.set(tree).ok();+ Ok(image)+ }+ Err(error) => Err(error),+ };+ render_image.set(value).ok();+ Self::on_render_complete(this, fallback_image, cx);+ }});Self {render_image,+ parsed_svg,fallback_image,+ rasterized_scale: zoom,_task: task,}}+ fn new_from_parsed(+ parsed_svg: Arc<ParsedSvg>,+ scale_factor: f32,+ rasterized_scale: f32,+ fallback_image: Option<(Arc<RenderImage>, f32)>,+ cx: &mut Context<Markdown>,+ ) -> Self {+ let render_image = Arc::new(OnceLock::<anyhow::Result<Arc<RenderImage>>>::new());+ let parsed_svg_cell = Arc::new(OnceLock::new());+ parsed_svg_cell.set(parsed_svg.clone()).ok();+ let svg_renderer = cx.svg_renderer();++ let task = cx.spawn({+ let render_image = render_image.clone();+ let fallback_image = fallback_image.clone();+ async move |this, cx| {+ let value = cx+ .background_spawn(async move {+ svg_renderer+ .render_parsed(&parsed_svg, scale_factor)+ .map_err(|error| anyhow::anyhow!("{error}"))+ })+ .await;+ render_image.set(value).ok();+ Self::on_render_complete(this, fallback_image, cx);+ }+ });++ Self {+ render_image,+ parsed_svg: parsed_svg_cell,+ fallback_image,+ rasterized_scale,+ _task: task,+ }+ }++ fn on_render_complete(+ this: gpui::WeakEntity<Markdown>,+ fallback_image: Option<(Arc<RenderImage>, f32)>,+ cx: &mut gpui::AsyncApp,+ ) {+ this.update(cx, |_, cx| {+ // The fallback will no longer be painted now that the real render+ // is available, so its GPU texture can be released.+ if let Some((fallback_image, _)) = fallback_image {+ cx.drop_image(fallback_image, None);+ }+ cx.notify();+ })+ .ok();+ }++ fn drop_images(&self, cx: &mut App) {+ if let Some(Ok(render_image)) = self.render_image.get() {+ cx.drop_image(render_image.clone(), None);+ }+ if let Some((fallback_image, _)) = self.fallback_image.clone() {+ cx.drop_image(fallback_image, None);+ }+ }+#[cfg(test)]fn new_for_test(render_image: Option<Arc<RenderImage>>,fallback_image: Option<Arc<RenderImage>>,+ parsed_svg: Option<Arc<ParsedSvg>>,) -> Self {let result = Arc::new(OnceLock::new());if let Some(render_image) = render_image {let _ = result.set(Ok(render_image));}+ let parsed_svg_cell = Arc::new(OnceLock::new());+ if let Some(parsed_svg) = parsed_svg {+ let _ = parsed_svg_cell.set(parsed_svg);+ }Self {render_image: result,- fallback_image,+ parsed_svg: parsed_svg_cell,+ fallback_image: fallback_image.map(|image| (image, 1.0)),+ rasterized_scale: 1.0,_task: Task::ready(()),}}@@ -310,6 +502,72 @@ pub(crate) fn extract_mermaid_diagrams(mermaid_diagrams}+/// The natural (zoom 1.0, unfitted) logical size of a diagram, recovered from+/// one of its rasters.+///+/// Mermaid rasters always come from `SvgRenderer::render_parsed`, whose images+/// have a device scale of [`SMOOTH_SVG_SCALE_FACTOR`]; dividing by it and by+/// the scale the raster was made at recovers the natural size, regardless of+/// which raster is currently cached.+fn mermaid_base_size(image: &RenderImage, rasterized_scale: f32) -> Size<Pixels> {+ let device_size = image.size(0);+ let device_scale = SMOOTH_SVG_SCALE_FACTOR * rasterized_scale;+ size(+ px(device_size.width.0 as f32 / device_scale),+ px(device_size.height.0 as f32 / device_scale),+ )+}++fn mermaid_display_size(base_size: Size<Pixels>, display_scale: f32) -> Size<Pixels> {+ size(+ base_size.width * display_scale,+ base_size.height * display_scale,+ )+}++/// The number of zoom ticks represented by a scroll-wheel event.+///+/// A discrete wheel notch arrives as one `Lines` event whose magnitude varies+/// by platform and device (1 or 3 lines are both common), so the delta is+/// clamped to a single tick: every notch is exactly one step. Precise (pixel)+/// deltas from trackpads arrive as many small events, each contributing a+/// fractional tick, so a gesture zooms smoothly at the same overall rate.+fn mermaid_zoom_ticks(delta: ScrollDelta) -> f32 {+ match delta {+ ScrollDelta::Lines(lines) => lines.y,+ ScrollDelta::Pixels(pixels) => f32::from(pixels.y) / PIXELS_PER_ZOOM_TICK,+ }+ .clamp(-1.0, 1.0)+}++fn on_mermaid_zoom_scroll(+ markdown: Entity<Markdown>,+ source_offset: usize,+ on_zoom: Option<MermaidZoomCallback>,+) -> impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static {+ move |event, window, cx| {+ if !(event.modifiers.control || event.modifiers.platform) {+ return;+ }+ let scroll_ticks = mermaid_zoom_ticks(event.delta);+ if scroll_ticks != 0.0 {+ let zoom_changed = markdown.update(cx, |markdown, cx| {+ let current_zoom = markdown.mermaid_zoom_level(source_offset);+ let new_zoom = current_zoom + scroll_ticks * MERMAID_ZOOM_STEP;+ markdown.set_mermaid_zoom_level(source_offset, new_zoom, cx);+ markdown.mermaid_zoom_level(source_offset) != current_zoom+ });+ // Only notify when the zoom actually changed. A no-op zoom (e.g.+ // clamped at the min/max) must not pause tail-following, since that+ // would disable following while still at the bottom.+ if zoom_changed && let Some(on_zoom) = &on_zoom {+ on_zoom(window, cx);+ }+ }+ cx.stop_propagation();+ }+}+pub(crate) fn render_mermaid_diagram(parsed: &ParsedMarkdownMermaidDiagram,mermaid_state: &MermaidState,@@ -317,13 +575,15 @@ pub(crate) fn render_mermaid_diagram(markdown: Entity<Markdown>,source_offset: usize,showing_code: bool,+ zoom: f32,copy_button_visibility: CopyButtonVisibility,+ on_zoom: Option<MermaidZoomCallback>,+ window: &mut Window,+ cx: &mut App,) -> AnyElement {let cached = mermaid_state.cache.get(&parsed.contents);let render_result = cached.and_then(|cached| cached.render_image.get());let show_interactive = copy_button_visibility != CopyButtonVisibility::Hidden;- // Preview keeps diagrams at natural size + scroll instead of crushing them via max_w_full (#61051).- let allow_overflow_x = style.code_block_overflow_x_scroll;let code = parsed.contents.contents.clone();@@ -335,7 +595,25 @@ pub(crate) fn render_mermaid_diagram(let body = if showing_code {render_mermaid_code_view(&parsed.contents.contents)} else {- render_mermaid_image(render_image.clone(), allow_overflow_x, source_offset)+ let rasterized_scale = cached.map_or(1.0, |cached| cached.rasterized_scale);+ let image_element =+ img(ImageSource::Render(render_image.clone())).with_fallback(|| {+ Label::new("Failed to Load Mermaid Diagram").into_any_element()+ });+ let scroll_handle = markdown.update(cx, |markdown, _| {+ markdown.mermaid_scroll_handle(source_offset)+ });+ let base_size = mermaid_base_size(render_image, rasterized_scale);+ let display_size = mermaid_display_size(base_size, zoom);+ let body = mermaid_scroll_container(+ markdown.clone(),+ source_offset,+ &scroll_handle,+ on_zoom.clone(),+ )+ .child(image_element.w(display_size.width).h(display_size.height))+ .into_any_element();+ with_mermaid_horizontal_scrollbar(source_offset, &scroll_handle, body, window, cx)};container@@ -348,10 +626,12 @@ pub(crate) fn render_mermaid_diagram(}).child(body).when(show_interactive, |container| {- container.child(render_mermaid_copy_button(+ container.child(render_mermaid_overlay_controls(source_offset,code.to_string(),+ (!showing_code && zoom != 1.0).then_some(zoom),markdown,+ on_zoom,))}).into_any_element()@@ -361,38 +641,70 @@ pub(crate) fn render_mermaid_diagram(container.child(render_mermaid_code_view(&parsed.contents.contents)).when(show_interactive, |container| {- container.child(render_mermaid_copy_button(+ container.child(render_mermaid_overlay_controls(source_offset,code.to_string(),+ None,markdown,+ on_zoom,))}).into_any_element()}None => {// Still rendering- if let Some(fallback) = cached.and_then(|cached| cached.fallback_image.as_ref()) {- container- .child(+ if let Some((fallback, fallback_scale)) =+ cached.and_then(|cached| cached.fallback_image.clone())+ {+ let fallback_element =+ img(ImageSource::Render(fallback.clone())).with_fallback(|| {div()- .child(render_mermaid_image(- fallback.clone(),- allow_overflow_x,- source_offset,- ))- .with_animation(- "mermaid-fallback-pulse",- Animation::new(Duration::from_secs(2))- .repeat()- .with_easing(pulsating_between(0.6, 1.0)),- |element, delta| element.opacity(delta),- ),- )+ .child(Label::new("Failed to load mermaid diagram"))+ .into_any_element()+ });+ let scroll_handle = markdown.update(cx, |markdown, _| {+ markdown.mermaid_scroll_handle(source_offset)+ });+ let base_size = mermaid_base_size(&fallback, fallback_scale);+ let display_size = mermaid_display_size(base_size, zoom);+ // The fallback is the prior raster shown at the new size while+ // the sharper one renders; keep it static so swapping rasters+ // (e.g. on zoom) is seamless rather than flashing.+ let inner = mermaid_scroll_container(+ markdown.clone(),+ source_offset,+ &scroll_handle,+ on_zoom.clone(),+ )+ .child(+ fallback_element+ .w(display_size.width)+ .h(display_size.height),+ )+ .into_any_element();+ let body = with_mermaid_horizontal_scrollbar(+ source_offset,+ &scroll_handle,+ inner,+ window,+ cx,+ );+ container+ .when(show_interactive, |container| {+ container.child(render_mermaid_tab_header(+ source_offset,+ showing_code,+ markdown.clone(),+ ))+ })+ .child(body).when(show_interactive, |container| {- container.child(render_mermaid_copy_button(+ container.child(render_mermaid_overlay_controls(source_offset,code.to_string(),+ (zoom != 1.0).then_some(zoom),markdown,+ on_zoom,))}).into_any_element()@@ -415,10 +727,12 @@ pub(crate) fn render_mermaid_diagram(),).when(show_interactive, |container| {- container.child(render_mermaid_copy_button(+ container.child(render_mermaid_overlay_controls(source_offset,code.to_string(),+ None,markdown,+ on_zoom,))}).into_any_element()@@ -427,28 +741,61 @@ pub(crate) fn render_mermaid_diagram(}}-/// Renders a mermaid diagram image, scrolling at intrinsic size in preview or fit-to-pane elsewhere.-fn render_mermaid_image(- render_image: Arc<RenderImage>,- allow_overflow_x: bool,+/// The horizontal scroll container wrapping a mermaid raster. The element id+/// and the [`ScrollHandle`] identity are both stable per source offset so the+/// scroll position survives raster swaps and re-rasters. Diagrams keep their+/// natural (zoomed) size and scroll instead of being crushed via max_w_full+/// (#61051).+fn mermaid_scroll_container(+ markdown: Entity<Markdown>,+ source_offset: usize,+ scroll_handle: &ScrollHandle,+ on_zoom: Option<MermaidZoomCallback>,+) -> Stateful<Div> {+ let mut container = div()+ .id(ElementId::named_usize(+ "mermaid-diagram-body",+ source_offset,+ ))+ .w_full()+ .overflow_x_scroll()+ .track_scroll(scroll_handle)+ .on_scroll_wheel(on_mermaid_zoom_scroll(markdown, source_offset, on_zoom));+ // Without this, gpui maps vertical wheel deltas onto the x axis for+ // x-only scroll containers (see `paint_scroll_listener` in gpui's div),+ // hijacking plain vertical scrolls. Restricting to the actual axis lets+ // vertical deltas propagate to the surrounding view, and means a+ // ctrl+vertical-scroll (zoom gesture) never moves this container either,+ // since its delta.x is zero.+ container.style().restrict_scroll_to_axis = Some(true);+ container+}++fn with_mermaid_horizontal_scrollbar(source_offset: usize,+ scroll_handle: &ScrollHandle,+ body: AnyElement,+ window: &mut Window,+ cx: &mut App,) -> AnyElement {- let image = img(ImageSource::Render(render_image))- .with_fallback(|| Label::new("Failed to Load Mermaid Diagram").into_any_element());-- if allow_overflow_x {- div()- .id(("mermaid-scroll", source_offset))- .w_full()- .map(|mut container| {- container.style().restrict_scroll_to_axis = Some(true);- container.overflow_x_scroll()- })- .child(image)- .into_any_element()- } else {- div().w_full().child(image.max_w_full()).into_any_element()- }+ // Always show the scrollbar (rather than autohiding) so it's clear a+ // zoomed diagram can be scrolled. It only appears when the content+ // actually overflows, since the thumb isn't drawn when there's nothing to+ // scroll.+ let scrollbars = Scrollbars::always_visible(ScrollAxes::Horizontal)+ .id(("mermaid-diagram-scrollbar", source_offset))+ .tracked_scroll_handle(scroll_handle)+ .with_track_along(+ ScrollAxes::Horizontal,+ cx.theme().colors().editor_background,+ )+ .notify_content();++ div()+ .w_full()+ .custom_scrollbars(scrollbars, window, cx)+ .child(body)+ .into_any_element()}fn render_mermaid_tab_header(@@ -503,6 +850,71 @@ fn render_mermaid_tab_header()}+/// The overlay controls anchored to the top-right corner of a diagram: an+/// optional "Zoom NNN%" readout with a reset button (shown only while zoomed+/// away from the natural size) followed by the hover-revealed copy button.+fn render_mermaid_overlay_controls(+ source_offset: usize,+ code: String,+ zoom: Option<f32>,+ markdown: Entity<Markdown>,+ on_zoom: Option<MermaidZoomCallback>,+) -> impl IntoElement {+ h_flex()+ .absolute()+ .top_1()+ .right_1()+ .gap_0p5()+ .when_some(zoom, |this, zoom| {+ this.child(render_mermaid_zoom_indicator(+ source_offset,+ zoom,+ markdown.clone(),+ on_zoom,+ ))+ })+ .child(render_mermaid_copy_button(source_offset, code, markdown))+}++/// A "Zoom NNN%" readout paired with a reset button, styled like the adjacent+/// copy button. Shown only while the diagram is zoomed away from its natural+/// size, so it doubles as an affordance that the zoom can be reset.+fn render_mermaid_zoom_indicator(+ source_offset: usize,+ zoom: f32,+ markdown: Entity<Markdown>,+ on_zoom: Option<MermaidZoomCallback>,+) -> impl IntoElement {+ let percentage = (zoom * 100.0).round() as i32;++ h_flex()+ .gap_0p5()+ .child(+ Label::new(format!("Zoom {percentage}%"))+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .child(+ IconButton::new(+ ElementId::named_usize("mermaid-zoom-reset", source_offset),+ IconName::RotateCcw,+ )+ .icon_size(IconSize::Small)+ .icon_color(Color::Muted)+ .tooltip(Tooltip::text("Reset Zoom"))+ .on_click(move |_event, window, cx| {+ let zoom_changed = markdown.update(cx, |markdown, cx| {+ let current_zoom = markdown.mermaid_zoom_level(source_offset);+ markdown.set_mermaid_zoom_level(source_offset, 1.0, cx);+ markdown.mermaid_zoom_level(source_offset) != current_zoom+ });+ if zoom_changed && let Some(on_zoom) = &on_zoom {+ on_zoom(window, cx);+ }+ }),+ )+}+fn render_mermaid_copy_button(source_offset: usize,code: String,@@ -513,30 +925,28 @@ fn render_mermaid_copy_button(source_offset.to_string().into(),);- div().absolute().top_1().right_1().justify_end().child(- CopyButton::new(id.clone(), code.clone())- .visible_on_hover("code_block")- .custom_on_click({- move |_window, cx| {- let id = id.clone();- markdown.update(cx, |this, cx| {- this.copied_code_blocks.insert(id.clone());- cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));- cx.spawn(async move |this, cx| {- cx.background_executor().timer(Duration::from_secs(2)).await;- cx.update(|cx| {- this.update(cx, |this, cx| {- this.copied_code_blocks.remove(&id);- cx.notify();- })+ CopyButton::new(id.clone(), code.clone())+ .visible_on_hover("code_block")+ .custom_on_click({+ move |_window, cx| {+ let id = id.clone();+ markdown.update(cx, |this, cx| {+ this.copied_code_blocks.insert(id.clone());+ cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));+ cx.spawn(async move |this, cx| {+ cx.background_executor().timer(Duration::from_secs(2)).await;+ cx.update(|cx| {+ this.update(cx, |this, cx| {+ this.copied_code_blocks.remove(&id);+ cx.notify();})- .ok();})- .detach();- });- }- }),- )+ .ok();+ })+ .detach();+ });+ }+ })}fn render_mermaid_code_view(contents: &SharedString) -> AnyElement {@@ -549,16 +959,21 @@ fn render_mermaid_code_view(contents: &SharedString) -> AnyElement {#[cfg(test)]mod tests {use super::{- CachedMermaidDiagram, MermaidDiagramCache, MermaidState,+ CachedMermaidDiagram, MermaidDiagramCache, MermaidState, ParsedMarkdownMermaidDiagram,ParsedMarkdownMermaidDiagramContents, extract_mermaid_diagrams, parse_mermaid_info,};use crate::{- CodeBlockRenderer, CopyButtonVisibility, Markdown, MarkdownElement, MarkdownOptions,- MarkdownStyle, WrapButtonVisibility,+ CodeBlockRenderer, CopyButtonVisibility, MERMAID_ZOOM_DEBOUNCE, Markdown, MarkdownElement,+ MarkdownOptions, MarkdownStyle, WrapButtonVisibility,};use collections::HashMap;- use gpui::{Context, IntoElement, Render, RenderImage, TestAppContext, Window, size};+ use gpui::{+ Context, Entity, IntoElement, Render, RenderImage, TestAppContext, Window, point, size,+ };+ use std::cell::RefCell;+ use std::rc::Rc;use std::sync::Arc;+ use std::time::Duration;use ui::prelude::*;fn ensure_theme_initialized(cx: &mut TestAppContext) {@@ -572,6 +987,51 @@ mod tests {});}+ /// Renders a [`MarkdownElement`] beneath a throwaway view (mirroring how+ /// elements are always rendered in production) and captures the+ /// [`crate::RenderedText`] produced by its layout. Mermaid diagram bodies+ /// are scroll containers, whose paint requires a current view, so the+ /// element can't be drawn bare with `cx.draw`.+ fn draw_markdown_element(+ markdown: Entity<Markdown>,+ cx: &mut gpui::VisualTestContext,+ ) -> crate::RenderedText {+ struct CaptureRenderedText {+ markdown: Entity<Markdown>,+ rendered_text: Rc<RefCell<Option<crate::RenderedText>>>,+ }++ impl Render for CaptureRenderedText {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let element = MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())+ .code_block_renderer(CodeBlockRenderer::Default {+ copy_button_visibility: CopyButtonVisibility::Hidden,+ wrap_button_visibility: WrapButtonVisibility::Hidden,+ border: false,+ })+ .on_render({+ let rendered_text = self.rendered_text.clone();+ move |text| *rendered_text.borrow_mut() = Some(text)+ });+ div().child(element)+ }+ }++ let rendered_text = Rc::new(RefCell::new(None));+ cx.draw(Default::default(), size(px(600.0), px(600.0)), {+ let rendered_text = rendered_text.clone();+ |_window, cx| {+ cx.new(|_| CaptureRenderedText {+ markdown,+ rendered_text,+ })+ .into_any_element()+ }+ });+ let rendered_text = rendered_text.borrow_mut().take();+ rendered_text.expect("markdown element should have been laid out")+ }+fn render_markdown_with_options(markdown: &str,options: MarkdownOptions,@@ -592,20 +1052,7 @@ mod tests {Markdown::new_with_options(markdown.to_string().into(), None, None, options, cx)});cx.run_until_parked();- let (rendered, _) = cx.draw(- Default::default(),- size(px(600.0), px(600.0)),- |_window, _cx| {- MarkdownElement::new(markdown, MarkdownStyle::default()).code_block_renderer(- CodeBlockRenderer::Default {- copy_button_visibility: CopyButtonVisibility::Hidden,- wrap_button_visibility: WrapButtonVisibility::Hidden,- border: false,- },- )- },- );- rendered.text+ draw_markdown_element(markdown, cx)}fn mock_render_image(cx: &mut TestAppContext) -> Arc<RenderImage> {@@ -644,6 +1091,7 @@ mod tests {.iter().position(|diagram| diagram == &new_content)?;MermaidState::get_fallback_image(idx, old_full_order, new_full_order.len(), cache)+ .map(|(image, _)| image)}#[test]@@ -728,6 +1176,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);cache.insert(@@ -735,6 +1184,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(svg_b.clone()),None,+ None,)),);cache.insert(@@ -742,6 +1192,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);@@ -762,6 +1213,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);cache.insert(@@ -769,6 +1221,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);@@ -790,6 +1243,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);cache.insert(@@ -797,6 +1251,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(None,Some(original_svg.clone()),+ None,)),);cache.insert(@@ -804,6 +1259,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);@@ -833,6 +1289,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(svg_a.clone()),None,+ None,)),);cache.insert(@@ -840,6 +1297,7 @@ mod tests {Arc::new(CachedMermaidDiagram::new_for_test(Some(mock_render_image(cx)),None,+ None,)),);@@ -848,6 +1306,426 @@ mod tests {assert_eq!(fallback.as_ref().map(|image| image.id), Some(svg_a.id));}+ #[gpui::test]+ fn test_mermaid_rerasterize_reuses_parsed_svg(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);++ let markdown = cx.new(|cx| Markdown::new("".into(), None, None, cx));++ let (parsed_svg, original_image) = markdown.update(cx, |_, cx| {+ let svg_renderer = cx.svg_renderer();+ let parsed_svg = Arc::new(+ svg_renderer+ .parse_svg(+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>"#,+ )+ .unwrap(),+ );+ let original_image = svg_renderer.render_parsed(&parsed_svg, 1.0).unwrap();+ (parsed_svg, original_image)+ });++ let contents = mermaid_contents("graph A");+ let mut state = MermaidState::default();+ state.cache.insert(+ contents.clone(),+ Arc::new(CachedMermaidDiagram::new_for_test(+ Some(original_image.clone()),+ None,+ Some(parsed_svg),+ )),+ );++ markdown.update(cx, |_, cx| state.rerasterize_diagram(&contents, 2.0, cx));++ let cached = state.cache.get(&contents).unwrap();+ assert!(+ cached.render_image.get().is_none(),+ "the new raster should still be pending"+ );+ assert_eq!(cached.rasterized_scale, 2.0);+ assert_eq!(+ cached+ .fallback_image+ .as_ref()+ .map(|(image, zoom)| (image.id, *zoom)),+ Some((original_image.id, 1.0)),+ "the old raster should keep being displayed while the new one is pending"+ );++ cx.run_until_parked();++ let cached = state.cache.get(&contents).unwrap();+ let new_image = cached+ .render_image+ .get()+ .expect("render should have completed")+ .as_ref()+ .expect("render should have succeeded");+ let original_size = original_image.size(0);+ let new_size = new_image.size(0);+ assert_eq!(new_size.width.0, original_size.width.0 * 2);+ assert_eq!(new_size.height.0, original_size.height.0 * 2);++ // Re-rasterizing at the zoom the entry is already rasterized at is a+ // no-op.+ let entry_before = Arc::as_ptr(state.cache.get(&contents).unwrap());+ markdown.update(cx, |_, cx| state.rerasterize_diagram(&contents, 2.0, cx));+ assert_eq!(+ Arc::as_ptr(state.cache.get(&contents).unwrap()),+ entry_before+ );+ }++ #[gpui::test]+ fn test_mermaid_zoom_rerasterize_is_debounced(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);++ let markdown = cx.new(|cx| Markdown::new("".into(), None, None, cx));++ let (parsed_svg, original_image) = markdown.update(cx, |_, cx| {+ let svg_renderer = cx.svg_renderer();+ let parsed_svg = Arc::new(+ svg_renderer+ .parse_svg(+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>"#,+ )+ .unwrap(),+ );+ let original_image = svg_renderer.render_parsed(&parsed_svg, 1.0).unwrap();+ (parsed_svg, original_image)+ });++ let contents = mermaid_contents("graph A");+ let source_offset = 0;+ markdown.update(cx, |markdown, _| {+ markdown.parsed_markdown.mermaid_diagrams.insert(+ source_offset,+ ParsedMarkdownMermaidDiagram {+ content_range: 0..contents.contents.len(),+ contents: contents.clone(),+ },+ );+ markdown.mermaid_state.cache.insert(+ contents.clone(),+ Arc::new(CachedMermaidDiagram::new_for_test(+ Some(original_image.clone()),+ None,+ Some(parsed_svg),+ )),+ );+ });++ let half_debounce = MERMAID_ZOOM_DEBOUNCE / 2;++ markdown.update(cx, |markdown, cx| {+ markdown.set_mermaid_zoom_level(source_offset, 1.5, cx)+ });+ cx.executor().advance_clock(half_debounce);+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ let cached = markdown.mermaid_state.cache.get(&contents).unwrap();+ assert_eq!(+ cached.rasterized_scale, 1.0,+ "no re-raster before the debounce elapses"+ );+ });++ // A second zoom change within the debounce window restarts the timer.+ markdown.update(cx, |markdown, cx| {+ markdown.set_mermaid_zoom_level(source_offset, 2.0, cx)+ });+ cx.executor().advance_clock(half_debounce);+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ let cached = markdown.mermaid_state.cache.get(&contents).unwrap();+ assert_eq!(+ cached.rasterized_scale, 1.0,+ "the second zoom change should restart the debounce timer"+ );+ });++ cx.executor()+ .advance_clock(half_debounce + Duration::from_millis(1));+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ let cached = markdown.mermaid_state.cache.get(&contents).unwrap();+ assert_eq!(cached.rasterized_scale, 2.0);+ let new_image = cached+ .render_image+ .get()+ .expect("render should have completed")+ .as_ref()+ .expect("render should have succeeded");+ let original_size = original_image.size(0);+ let new_size = new_image.size(0);+ assert_eq!(new_size.width.0, original_size.width.0 * 2);+ assert_eq!(new_size.height.0, original_size.height.0 * 2);+ });+ }++ #[test]+ fn test_mermaid_zoom_ticks_is_one_step_per_notch() {+ use gpui::{ScrollDelta, point, px};++ use super::mermaid_zoom_ticks;++ // Discrete wheel notches report varying line counts per platform and+ // device; all must count as exactly one tick.+ for lines in [1.0, 3.0, 5.0] {+ assert_eq!(+ mermaid_zoom_ticks(ScrollDelta::Lines(point(0.0, lines))),+ 1.0+ );+ assert_eq!(+ mermaid_zoom_ticks(ScrollDelta::Lines(point(0.0, -lines))),+ -1.0+ );+ }++ // Precise deltas contribute fractional ticks, capped at one tick.+ let half_tick = mermaid_zoom_ticks(ScrollDelta::Pixels(point(px(0.0), px(10.0))));+ assert!(half_tick > 0.0 && half_tick < 1.0);+ assert_eq!(+ mermaid_zoom_ticks(ScrollDelta::Pixels(point(px(0.0), px(500.0)))),+ 1.0+ );++ // Horizontal-only scrolling must not zoom.+ assert_eq!(mermaid_zoom_ticks(ScrollDelta::Lines(point(2.0, 0.0))), 0.0);+ }++ #[gpui::test]+ fn test_mermaid_zoom_snap_and_clamp(cx: &mut TestAppContext) {+ let markdown = cx.new(|cx| Markdown::new("".into(), None, None, cx));++ markdown.update(cx, |markdown, cx| {+ // With no raster or layout to compute a fit-to-width scale from,+ // the minimum zoom is 1.0.+ markdown.set_mermaid_zoom_level(0, 0.05, cx);+ assert_eq!(markdown.mermaid_zoom_level(0), 1.0);++ markdown.set_mermaid_zoom_level(0, 10.0, cx);+ assert_eq!(markdown.mermaid_zoom_level(0), 2.0);++ // Values close to 1.0 snap back to the default.+ markdown.set_mermaid_zoom_level(0, 1.04, cx);+ assert_eq!(markdown.mermaid_zoom_level(0), 1.0);++ markdown.set_mermaid_zoom_level(0, 2.0, cx);+ markdown.set_mermaid_zoom_level(0, 0.96, cx);+ assert_eq!(markdown.mermaid_zoom_level(0), 1.0);++ markdown.set_mermaid_zoom_level(0, 1.06, cx);+ assert_eq!(markdown.mermaid_zoom_level(0), 1.06);+ });+ }++ #[gpui::test]+ fn test_mermaid_zoom_to_fit_tracks_container_width(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);++ let markdown = cx.new(|cx| Markdown::new("".into(), None, None, cx));++ // A raster whose natural (zoom 1.0) width is 200px.+ let (parsed_svg, image) = markdown.update(cx, |_, cx| {+ let svg_renderer = cx.svg_renderer();+ let parsed_svg = Arc::new(+ svg_renderer+ .parse_svg(+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100"></svg>"#,+ )+ .unwrap(),+ );+ let image = svg_renderer.render_parsed(&parsed_svg, 1.0).unwrap();+ (parsed_svg, image)+ });++ let contents = mermaid_contents("graph A");+ let source_offset = 0;+ markdown.update(cx, |markdown, _| {+ markdown.parsed_markdown.mermaid_diagrams.insert(+ source_offset,+ ParsedMarkdownMermaidDiagram {+ content_range: 0..contents.contents.len(),+ contents: contents.clone(),+ },+ );+ markdown.mermaid_state.cache.insert(+ contents.clone(),+ Arc::new(CachedMermaidDiagram::new_for_test(+ Some(image),+ None,+ Some(parsed_svg),+ )),+ );+ markdown+ .mermaid_views+ .entry(source_offset)+ .or_default()+ .container_width_for_test = Some(px(100.));+ });++ // Zooming out past the floor clamps to fit-to-width (100 / 200).+ markdown.update(cx, |markdown, cx| {+ markdown.set_mermaid_zoom_level(source_offset, 0.05, cx);+ assert_eq!(markdown.mermaid_zoom_level(source_offset), 0.5);+ });++ // A fully zoomed-out diagram stays stuck to fit-to-width when the+ // container is resized.+ markdown.update(cx, |markdown, cx| {+ markdown+ .mermaid_views+ .get_mut(&source_offset)+ .unwrap()+ .container_width_for_test = Some(px(150.));+ assert_eq!(+ markdown.effective_mermaid_zoom_level(source_offset, cx),+ 0.75+ );+ assert_eq!(markdown.mermaid_zoom_level(source_offset), 0.75);+ });++ // Zooming in one step starts from the tracked fit-to-width zoom+ // instead of jumping, and stops tracking the container width.+ markdown.update(cx, |markdown, cx| {+ let zoom = markdown.mermaid_zoom_level(source_offset);+ markdown.set_mermaid_zoom_level(source_offset, zoom + 0.1, cx);+ assert!((markdown.mermaid_zoom_level(source_offset) - 0.85).abs() < 1e-5);++ markdown+ .mermaid_views+ .get_mut(&source_offset)+ .unwrap()+ .container_width_for_test = Some(px(100.));+ assert!(+ (markdown.effective_mermaid_zoom_level(source_offset, cx) - 0.85).abs() < 1e-5,+ "a zoom above the floor must not track container resizes"+ );+ });++ // Resetting to the natural size never tracks the container width.+ markdown.update(cx, |markdown, cx| {+ markdown.set_mermaid_zoom_level(source_offset, 1.0, cx);+ markdown+ .mermaid_views+ .get_mut(&source_offset)+ .unwrap()+ .container_width_for_test = Some(px(150.));+ assert_eq!(+ markdown.effective_mermaid_zoom_level(source_offset, cx),+ 1.0+ );+ });+ }++ #[gpui::test]+ fn test_mermaid_zoom_retained_across_reparse(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);++ let source = "```mermaid\ngraph TD;\n```";+ let markdown = cx.new(|cx| {+ Markdown::new_with_options(+ source.into(),+ None,+ None,+ MarkdownOptions {+ render_mermaid_diagrams: true,+ ..Default::default()+ },+ cx,+ )+ });+ cx.run_until_parked();++ let source_offset = markdown.read_with(cx, |markdown, _| {+ *markdown+ .parsed_markdown+ .mermaid_diagrams+ .keys()+ .next()+ .expect("the mermaid diagram should have been parsed")+ });+ markdown.update(cx, |markdown, cx| {+ markdown.set_mermaid_zoom_level(source_offset, 2.0, cx)+ });++ // Appending after the diagram keeps its offset, so the zoom is+ // retained across the reparse.+ markdown.update(cx, |markdown, cx| {+ markdown.replace(format!("{source}\n\nmore text"), cx);+ });+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ assert_eq!(markdown.mermaid_zoom_level(source_offset), 2.0);+ });++ // Removing the diagram drops its zoom state.+ markdown.update(cx, |markdown, cx| {+ markdown.replace("plain text", cx);+ });+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ assert_eq!(markdown.mermaid_zoom_level(source_offset), 1.0);+ assert!(markdown.mermaid_views.is_empty());+ });+ }++ #[gpui::test]+ fn test_mermaid_scroll_handle_retained_across_reparse(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);++ let source = "```mermaid\ngraph TD;\n```";+ let markdown = cx.new(|cx| {+ Markdown::new_with_options(+ source.into(),+ None,+ None,+ MarkdownOptions {+ render_mermaid_diagrams: true,+ ..Default::default()+ },+ cx,+ )+ });+ cx.run_until_parked();++ let source_offset = markdown.read_with(cx, |markdown, _| {+ *markdown+ .parsed_markdown+ .mermaid_diagrams+ .keys()+ .next()+ .expect("the mermaid diagram should have been parsed")+ });+ let scroll_handle = markdown.update(cx, |markdown, _| {+ markdown.mermaid_scroll_handle(source_offset)+ });+ scroll_handle.set_offset(point(px(-42.0), px(0.0)));++ // Appending after the diagram keeps its offset, so the same scroll+ // handle (and thus the scroll position) is retained across the+ // reparse.+ markdown.update(cx, |markdown, cx| {+ markdown.replace(format!("{source}\n\nmore text"), cx);+ });+ cx.run_until_parked();+ let retained_handle = markdown.update(cx, |markdown, _| {+ markdown.mermaid_scroll_handle(source_offset)+ });+ assert_eq!(retained_handle.offset(), point(px(-42.0), px(0.0)));++ // Removing the diagram drops its scroll state.+ markdown.update(cx, |markdown, cx| {+ markdown.replace("plain text", cx);+ });+ cx.run_until_parked();+ markdown.read_with(cx, |markdown, _| {+ assert!(markdown.mermaid_views.is_empty());+ });+ }+#[gpui::test]fn test_mermaid_rendering_replaces_code_block_text(cx: &mut TestAppContext) {let rendered = render_markdown_with_options(@@ -907,23 +1785,16 @@ mod tests {.clone();markdown.mermaid_state.cache.insert(contents.clone(),- Arc::new(CachedMermaidDiagram::new_for_test(Some(render_image), None)),+ Arc::new(CachedMermaidDiagram::new_for_test(+ Some(render_image),+ None,+ None,+ )),);markdown.mermaid_state.order = vec![contents];});- let (rendered, _) = cx.draw(- Default::default(),- size(px(600.0), px(600.0)),- |_window, _cx| {- MarkdownElement::new(markdown.clone(), MarkdownStyle::default())- .code_block_renderer(CodeBlockRenderer::Default {- copy_button_visibility: CopyButtonVisibility::Hidden,- wrap_button_visibility: WrapButtonVisibility::Hidden,- border: false,- })- },- );+ let rendered_text = draw_markdown_element(markdown.clone(), cx);let mermaid_diagram = markdown.update(cx, |markdown, _| {markdown@@ -935,14 +1806,12 @@ mod tests {.clone()});assert!(- rendered- .text+ rendered_text.position_for_source_index(mermaid_diagram.content_range.start).is_some());assert!(- rendered- .text+ rendered_text.position_for_source_index(mermaid_diagram.content_range.end.saturating_sub(1)).is_some());diff --git a/crates/mermaid_render/Cargo.toml b/crates/mermaid_render/Cargo.tomlindex 580165f5466..434aad47195 100644--- a/crates/mermaid_render/Cargo.toml+++ b/crates/mermaid_render/Cargo.toml@@ -21,8 +21,13 @@ gpui.workspace = truemerman = { git = "https://github.com/zed-industries/merman", tag = "v0.6.2-with-patches", features = ["render"] }quick-xml.workspace = trueserde_json.workspace = true+tracing.workspace = true+ztracing.workspace = true[dev-dependencies]gpui = { workspace = true, features = ["test-support"] }mermaid_render = { path = ".", features = ["test-support"] }usvg.workspace = true++[package.metadata.cargo-machete]+ignored = ["tracing"]diff --git a/crates/mermaid_render/src/mermaid_render.rs b/crates/mermaid_render/src/mermaid_render.rsindex 8f9ee8f5ee2..9550c2646ad 100644--- a/crates/mermaid_render/src/mermaid_render.rs+++ b/crates/mermaid_render/src/mermaid_render.rs@@ -175,6 +175,7 @@ pub(crate) fn css_color(color: Hsla) -> String {pub use postprocess::util::text_color_for_background;/// See the [module-level docs][crate] for more info.+#[ztracing::instrument(skip_all)]pub fn render_to_svg(source: &str, theme: &MermaidTheme) -> Result<String> {let svg = render::render_mermaid(source, theme)?;let svg = postprocess::postprocess(&svg, theme)?;