markdown_renderer.rs

  1use crate::markdown_elements::{
  2    HeadingLevel, Link, MarkdownParagraph, MarkdownParagraphChunk, ParsedMarkdown,
  3    ParsedMarkdownBlockQuote, ParsedMarkdownCodeBlock, ParsedMarkdownElement,
  4    ParsedMarkdownHeading, ParsedMarkdownListItem, ParsedMarkdownListItemType, ParsedMarkdownTable,
  5    ParsedMarkdownTableAlignment, ParsedMarkdownTableRow,
  6};
  7use gpui::{
  8    AbsoluteLength, AnyElement, App, AppContext as _, ClipboardItem, Context, DefiniteLength, Div,
  9    Element, ElementId, Entity, HighlightStyle, Hsla, ImageSource, InteractiveText, IntoElement,
 10    Keystroke, Length, Modifiers, ParentElement, Render, Resource, SharedString, Styled,
 11    StyledText, TextStyle, WeakEntity, Window, div, img, rems,
 12};
 13use settings::Settings;
 14use std::{
 15    ops::{Mul, Range},
 16    sync::Arc,
 17    vec,
 18};
 19use theme::{ActiveTheme, SyntaxTheme, ThemeSettings};
 20use ui::{
 21    ButtonCommon, Clickable, Color, FluentBuilder, IconButton, IconName, IconSize,
 22    InteractiveElement, Label, LabelCommon, LabelSize, LinkPreview, Pixels, Rems,
 23    StatefulInteractiveElement, StyledExt, StyledImage, ToggleState, Tooltip, VisibleOnHover,
 24    h_flex, relative, tooltip_container, v_flex,
 25};
 26use workspace::{OpenOptions, OpenVisible, Workspace};
 27
 28type CheckboxClickedCallback = Arc<Box<dyn Fn(bool, Range<usize>, &mut Window, &mut App)>>;
 29
 30#[derive(Clone)]
 31pub struct RenderContext {
 32    workspace: Option<WeakEntity<Workspace>>,
 33    next_id: usize,
 34    buffer_font_family: SharedString,
 35    buffer_text_style: TextStyle,
 36    text_style: TextStyle,
 37    border_color: Hsla,
 38    text_color: Hsla,
 39    window_rem_size: Pixels,
 40    text_muted_color: Hsla,
 41    code_block_background_color: Hsla,
 42    code_span_background_color: Hsla,
 43    syntax_theme: Arc<SyntaxTheme>,
 44    indent: usize,
 45    checkbox_clicked_callback: Option<CheckboxClickedCallback>,
 46}
 47
 48impl RenderContext {
 49    pub fn new(
 50        workspace: Option<WeakEntity<Workspace>>,
 51        window: &mut Window,
 52        cx: &mut App,
 53    ) -> RenderContext {
 54        let theme = cx.theme().clone();
 55
 56        let settings = ThemeSettings::get_global(cx);
 57        let buffer_font_family = settings.buffer_font.family.clone();
 58        let mut buffer_text_style = window.text_style();
 59        buffer_text_style.font_family = buffer_font_family.clone();
 60        buffer_text_style.font_size = AbsoluteLength::from(settings.buffer_font_size(cx));
 61
 62        RenderContext {
 63            workspace,
 64            next_id: 0,
 65            indent: 0,
 66            buffer_font_family,
 67            buffer_text_style,
 68            text_style: window.text_style(),
 69            syntax_theme: theme.syntax().clone(),
 70            border_color: theme.colors().border,
 71            text_color: theme.colors().text,
 72            window_rem_size: window.rem_size(),
 73            text_muted_color: theme.colors().text_muted,
 74            code_block_background_color: theme.colors().surface_background,
 75            code_span_background_color: theme.colors().editor_document_highlight_read_background,
 76            checkbox_clicked_callback: None,
 77        }
 78    }
 79
 80    pub fn with_checkbox_clicked_callback(
 81        mut self,
 82        callback: impl Fn(bool, Range<usize>, &mut Window, &mut App) + 'static,
 83    ) -> Self {
 84        self.checkbox_clicked_callback = Some(Arc::new(Box::new(callback)));
 85        self
 86    }
 87
 88    fn next_id(&mut self, span: &Range<usize>) -> ElementId {
 89        let id = format!("markdown-{}-{}-{}", self.next_id, span.start, span.end);
 90        self.next_id += 1;
 91        ElementId::from(SharedString::from(id))
 92    }
 93
 94    /// HACK: used to have rems relative to buffer font size, so that things scale appropriately as
 95    /// buffer font size changes. The callees of this function should be reimplemented to use real
 96    /// relative sizing once that is implemented in GPUI
 97    pub fn scaled_rems(&self, rems: f32) -> Rems {
 98        return self
 99            .buffer_text_style
100            .font_size
101            .to_rems(self.window_rem_size)
102            .mul(rems);
103    }
104
105    /// This ensures that children inside of block quotes
106    /// have padding between them.
107    ///
108    /// For example, for this markdown:
109    ///
110    /// ```markdown
111    /// > This is a block quote.
112    /// >
113    /// > And this is the next paragraph.
114    /// ```
115    ///
116    /// We give padding between "This is a block quote."
117    /// and "And this is the next paragraph."
118    fn with_common_p(&self, element: Div) -> Div {
119        if self.indent > 0 {
120            element.pb(self.scaled_rems(0.75))
121        } else {
122            element
123        }
124    }
125}
126
127pub fn render_parsed_markdown(
128    parsed: &ParsedMarkdown,
129    workspace: Option<WeakEntity<Workspace>>,
130    window: &mut Window,
131    cx: &mut App,
132) -> Div {
133    let mut cx = RenderContext::new(workspace, window, cx);
134
135    v_flex().gap_3().children(
136        parsed
137            .children
138            .iter()
139            .map(|block| render_markdown_block(block, &mut cx)),
140    )
141}
142pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
143    use ParsedMarkdownElement::*;
144    match block {
145        Paragraph(text) => render_markdown_paragraph(text, cx),
146        Heading(heading) => render_markdown_heading(heading, cx),
147        ListItem(list_item) => render_markdown_list_item(list_item, cx),
148        Table(table) => render_markdown_table(table, cx),
149        BlockQuote(block_quote) => render_markdown_block_quote(block_quote, cx),
150        CodeBlock(code_block) => render_markdown_code_block(code_block, cx),
151        HorizontalRule(_) => render_markdown_rule(cx),
152    }
153}
154
155fn render_markdown_heading(parsed: &ParsedMarkdownHeading, cx: &mut RenderContext) -> AnyElement {
156    let size = match parsed.level {
157        HeadingLevel::H1 => 2.,
158        HeadingLevel::H2 => 1.5,
159        HeadingLevel::H3 => 1.25,
160        HeadingLevel::H4 => 1.,
161        HeadingLevel::H5 => 0.875,
162        HeadingLevel::H6 => 0.85,
163    };
164
165    let text_size = cx.scaled_rems(size);
166
167    // was `DefiniteLength::from(text_size.mul(1.25))`
168    // let line_height = DefiniteLength::from(text_size.mul(1.25));
169    let line_height = text_size * 1.25;
170
171    // was `rems(0.15)`
172    // let padding_top = cx.scaled_rems(0.15);
173    let padding_top = rems(0.15);
174
175    // was `.pb_1()` = `rems(0.25)`
176    // let padding_bottom = cx.scaled_rems(0.25);
177    let padding_bottom = rems(0.25);
178
179    let color = match parsed.level {
180        HeadingLevel::H6 => cx.text_muted_color,
181        _ => cx.text_color,
182    };
183    div()
184        .line_height(line_height)
185        .text_size(text_size)
186        .text_color(color)
187        .pt(padding_top)
188        .pb(padding_bottom)
189        .children(render_markdown_text(&parsed.contents, cx))
190        .whitespace_normal()
191        .into_any()
192}
193
194fn render_markdown_list_item(
195    parsed: &ParsedMarkdownListItem,
196    cx: &mut RenderContext,
197) -> AnyElement {
198    use ParsedMarkdownListItemType::*;
199
200    let padding = cx.scaled_rems((parsed.depth - 1) as f32);
201
202    let bullet = match &parsed.item_type {
203        Ordered(order) => format!("{}.", order).into_any_element(),
204        Unordered => "".into_any_element(),
205        Task(checked, range) => div()
206            .id(cx.next_id(range))
207            .mt(cx.scaled_rems(3.0 / 16.0))
208            .child(
209                MarkdownCheckbox::new(
210                    "checkbox",
211                    if *checked {
212                        ToggleState::Selected
213                    } else {
214                        ToggleState::Unselected
215                    },
216                    cx.clone(),
217                )
218                .when_some(
219                    cx.checkbox_clicked_callback.clone(),
220                    |this, callback| {
221                        this.on_click({
222                            let range = range.clone();
223                            move |selection, window, cx| {
224                                let checked = match selection {
225                                    ToggleState::Selected => true,
226                                    ToggleState::Unselected => false,
227                                    _ => return,
228                                };
229
230                                if window.modifiers().secondary() {
231                                    callback(checked, range.clone(), window, cx);
232                                }
233                            }
234                        })
235                    },
236                ),
237            )
238            .hover(|s| s.cursor_pointer())
239            .tooltip(|_, cx| {
240                InteractiveMarkdownElementTooltip::new(None, "toggle checkbox", cx).into()
241            })
242            .into_any_element(),
243    };
244    let bullet = div().mr(cx.scaled_rems(0.5)).child(bullet);
245
246    let contents: Vec<AnyElement> = parsed
247        .content
248        .iter()
249        .map(|c| render_markdown_block(c, cx))
250        .collect();
251
252    let item = h_flex()
253        .pl(DefiniteLength::Absolute(AbsoluteLength::Rems(padding)))
254        .items_start()
255        .children(vec![
256            bullet,
257            div().children(contents).pr(cx.scaled_rems(1.0)).w_full(),
258        ]);
259
260    cx.with_common_p(item).into_any()
261}
262
263/// # MarkdownCheckbox ///
264/// HACK: Copied from `ui/src/components/toggle.rs` to deal with scaling issues in markdown preview
265/// changes should be integrated into `Checkbox` in `toggle.rs` while making sure checkboxes elsewhere in the
266/// app are not visually affected
267#[derive(gpui::IntoElement)]
268struct MarkdownCheckbox {
269    id: ElementId,
270    toggle_state: ToggleState,
271    disabled: bool,
272    placeholder: bool,
273    on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
274    filled: bool,
275    style: ui::ToggleStyle,
276    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
277    label: Option<SharedString>,
278    render_cx: RenderContext,
279}
280
281impl MarkdownCheckbox {
282    /// Creates a new [`Checkbox`].
283    fn new(id: impl Into<ElementId>, checked: ToggleState, render_cx: RenderContext) -> Self {
284        Self {
285            id: id.into(),
286            toggle_state: checked,
287            disabled: false,
288            on_click: None,
289            filled: false,
290            style: ui::ToggleStyle::default(),
291            tooltip: None,
292            label: None,
293            placeholder: false,
294            render_cx,
295        }
296    }
297
298    /// Binds a handler to the [`Checkbox`] that will be called when clicked.
299    fn on_click(mut self, handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static) -> Self {
300        self.on_click = Some(Box::new(handler));
301        self
302    }
303
304    fn bg_color(&self, cx: &App) -> Hsla {
305        let style = self.style.clone();
306        match (style, self.filled) {
307            (ui::ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
308            (ui::ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
309            (ui::ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
310            (ui::ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
311            (ui::ToggleStyle::Custom(_), false) => gpui::transparent_black(),
312            (ui::ToggleStyle::Custom(color), true) => color.opacity(0.2),
313        }
314    }
315
316    fn border_color(&self, cx: &App) -> Hsla {
317        if self.disabled {
318            return cx.theme().colors().border_variant;
319        }
320
321        match self.style.clone() {
322            ui::ToggleStyle::Ghost => cx.theme().colors().border,
323            ui::ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
324            ui::ToggleStyle::Custom(color) => color.opacity(0.3),
325        }
326    }
327}
328
329impl gpui::RenderOnce for MarkdownCheckbox {
330    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
331        let group_id = format!("checkbox_group_{:?}", self.id);
332        let color = if self.disabled {
333            Color::Disabled
334        } else {
335            Color::Selected
336        };
337        let icon_size_small = IconSize::Custom(self.render_cx.scaled_rems(14. / 16.)); // was IconSize::Small
338        let icon = match self.toggle_state {
339            ToggleState::Selected => {
340                if self.placeholder {
341                    None
342                } else {
343                    Some(
344                        ui::Icon::new(IconName::Check)
345                            .size(icon_size_small)
346                            .color(color),
347                    )
348                }
349            }
350            ToggleState::Indeterminate => Some(
351                ui::Icon::new(IconName::Dash)
352                    .size(icon_size_small)
353                    .color(color),
354            ),
355            ToggleState::Unselected => None,
356        };
357
358        let bg_color = self.bg_color(cx);
359        let border_color = self.border_color(cx);
360        let hover_border_color = border_color.alpha(0.7);
361
362        let size = self.render_cx.scaled_rems(1.25); // was Self::container_size(); (20px)
363
364        let checkbox = h_flex()
365            .id(self.id.clone())
366            .justify_center()
367            .items_center()
368            .size(size)
369            .group(group_id.clone())
370            .child(
371                div()
372                    .flex()
373                    .flex_none()
374                    .justify_center()
375                    .items_center()
376                    .m(self.render_cx.scaled_rems(0.25)) // was .m_1
377                    .size(self.render_cx.scaled_rems(1.0)) // was .size_4
378                    .rounded(self.render_cx.scaled_rems(0.125)) // was .rounded_xs
379                    .border_1()
380                    .bg(bg_color)
381                    .border_color(border_color)
382                    .when(self.disabled, |this| this.cursor_not_allowed())
383                    .when(self.disabled, |this| {
384                        this.bg(cx.theme().colors().element_disabled.opacity(0.6))
385                    })
386                    .when(!self.disabled, |this| {
387                        this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
388                    })
389                    .when(self.placeholder, |this| {
390                        this.child(
391                            div()
392                                .flex_none()
393                                .rounded_full()
394                                .bg(color.color(cx).alpha(0.5))
395                                .size(self.render_cx.scaled_rems(0.25)), // was .size_1
396                        )
397                    })
398                    .children(icon),
399            );
400
401        h_flex()
402            .id(self.id)
403            .gap(ui::DynamicSpacing::Base06.rems(cx))
404            .child(checkbox)
405            .when_some(
406                self.on_click.filter(|_| !self.disabled),
407                |this, on_click| {
408                    this.on_click(move |_, window, cx| {
409                        on_click(&self.toggle_state.inverse(), window, cx)
410                    })
411                },
412            )
413            // TODO: Allow label size to be different from default.
414            // TODO: Allow label color to be different from muted.
415            .when_some(self.label, |this, label| {
416                this.child(Label::new(label).color(Color::Muted))
417            })
418            .when_some(self.tooltip, |this, tooltip| {
419                this.tooltip(move |window, cx| tooltip(window, cx))
420            })
421    }
422}
423
424fn paragraph_len(paragraphs: &MarkdownParagraph) -> usize {
425    paragraphs
426        .iter()
427        .map(|paragraph| match paragraph {
428            MarkdownParagraphChunk::Text(text) => text.contents.len(),
429            // TODO: Scale column width based on image size
430            MarkdownParagraphChunk::Image(_) => 1,
431        })
432        .sum()
433}
434
435fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
436    let mut max_lengths: Vec<usize> = vec![0; parsed.header.children.len()];
437
438    for (index, cell) in parsed.header.children.iter().enumerate() {
439        let length = paragraph_len(&cell);
440        max_lengths[index] = length;
441    }
442
443    for row in &parsed.body {
444        for (index, cell) in row.children.iter().enumerate() {
445            let length = paragraph_len(&cell);
446
447            if length > max_lengths[index] {
448                max_lengths[index] = length;
449            }
450        }
451    }
452
453    let total_max_length: usize = max_lengths.iter().sum();
454    let max_column_widths: Vec<f32> = max_lengths
455        .iter()
456        .map(|&length| length as f32 / total_max_length as f32)
457        .collect();
458
459    let header = render_markdown_table_row(
460        &parsed.header,
461        &parsed.column_alignments,
462        &max_column_widths,
463        true,
464        cx,
465    );
466
467    let body: Vec<AnyElement> = parsed
468        .body
469        .iter()
470        .map(|row| {
471            render_markdown_table_row(
472                row,
473                &parsed.column_alignments,
474                &max_column_widths,
475                false,
476                cx,
477            )
478        })
479        .collect();
480
481    cx.with_common_p(v_flex())
482        .w_full()
483        .child(header)
484        .children(body)
485        .into_any()
486}
487
488fn render_markdown_table_row(
489    parsed: &ParsedMarkdownTableRow,
490    alignments: &Vec<ParsedMarkdownTableAlignment>,
491    max_column_widths: &Vec<f32>,
492    is_header: bool,
493    cx: &mut RenderContext,
494) -> AnyElement {
495    let mut items = vec![];
496
497    for (index, cell) in parsed.children.iter().enumerate() {
498        let alignment = alignments
499            .get(index)
500            .copied()
501            .unwrap_or(ParsedMarkdownTableAlignment::None);
502
503        let contents = render_markdown_text(cell, cx);
504
505        let container = match alignment {
506            ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
507            ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
508            ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
509        };
510
511        let max_width = max_column_widths.get(index).unwrap_or(&0.0);
512        let mut cell = container
513            .w(Length::Definite(relative(*max_width)))
514            .h_full()
515            .children(contents)
516            .px_2()
517            .py_1()
518            .border_color(cx.border_color);
519
520        if is_header {
521            cell = cell.border_2()
522        } else {
523            cell = cell.border_1()
524        }
525
526        items.push(cell);
527    }
528
529    h_flex().children(items).into_any_element()
530}
531
532fn render_markdown_block_quote(
533    parsed: &ParsedMarkdownBlockQuote,
534    cx: &mut RenderContext,
535) -> AnyElement {
536    cx.indent += 1;
537
538    let children: Vec<AnyElement> = parsed
539        .children
540        .iter()
541        .map(|child| render_markdown_block(child, cx))
542        .collect();
543
544    cx.indent -= 1;
545
546    cx.with_common_p(div())
547        .child(
548            div()
549                .border_l_4()
550                .border_color(cx.border_color)
551                .pl_3()
552                .children(children),
553        )
554        .into_any()
555}
556
557fn render_markdown_code_block(
558    parsed: &ParsedMarkdownCodeBlock,
559    cx: &mut RenderContext,
560) -> AnyElement {
561    let body = if let Some(highlights) = parsed.highlights.as_ref() {
562        StyledText::new(parsed.contents.clone()).with_default_highlights(
563            &cx.buffer_text_style,
564            highlights.iter().filter_map(|(range, highlight_id)| {
565                highlight_id
566                    .style(cx.syntax_theme.as_ref())
567                    .map(|style| (range.clone(), style))
568            }),
569        )
570    } else {
571        StyledText::new(parsed.contents.clone())
572    };
573
574    let copy_block_button = IconButton::new("copy-code", IconName::Copy)
575        .icon_size(IconSize::Small)
576        .on_click({
577            let contents = parsed.contents.clone();
578            move |_, _window, cx| {
579                cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
580            }
581        })
582        .tooltip(Tooltip::text("Copy code block"))
583        .visible_on_hover("markdown-block");
584
585    cx.with_common_p(div())
586        .font_family(cx.buffer_font_family.clone())
587        .px_3()
588        .py_3()
589        .bg(cx.code_block_background_color)
590        .rounded_sm()
591        .child(body)
592        .child(
593            div()
594                .h_flex()
595                .absolute()
596                .right_1()
597                .top_1()
598                .child(copy_block_button),
599        )
600        .into_any()
601}
602
603fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
604    cx.with_common_p(div())
605        .children(render_markdown_text(parsed, cx))
606        .flex()
607        .flex_col()
608        .into_any_element()
609}
610
611fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
612    let mut any_element = vec![];
613    // these values are cloned in-order satisfy borrow checker
614    let syntax_theme = cx.syntax_theme.clone();
615    let workspace_clone = cx.workspace.clone();
616    let code_span_bg_color = cx.code_span_background_color;
617    let text_style = cx.text_style.clone();
618
619    for parsed_region in parsed_new {
620        match parsed_region {
621            MarkdownParagraphChunk::Text(parsed) => {
622                let element_id = cx.next_id(&parsed.source_range);
623
624                let highlights = gpui::combine_highlights(
625                    parsed.highlights.iter().filter_map(|(range, highlight)| {
626                        highlight
627                            .to_highlight_style(&syntax_theme)
628                            .map(|style| (range.clone(), style))
629                    }),
630                    parsed.regions.iter().zip(&parsed.region_ranges).filter_map(
631                        |(region, range)| {
632                            if region.code {
633                                Some((
634                                    range.clone(),
635                                    HighlightStyle {
636                                        background_color: Some(code_span_bg_color),
637                                        ..Default::default()
638                                    },
639                                ))
640                            } else {
641                                None
642                            }
643                        },
644                    ),
645                );
646                let mut links = Vec::new();
647                let mut link_ranges = Vec::new();
648                for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
649                    if let Some(link) = region.link.clone() {
650                        links.push(link);
651                        link_ranges.push(range.clone());
652                    }
653                }
654                let workspace = workspace_clone.clone();
655                let element = div()
656                    .child(
657                        InteractiveText::new(
658                            element_id,
659                            StyledText::new(parsed.contents.clone())
660                                .with_default_highlights(&text_style, highlights),
661                        )
662                        .tooltip({
663                            let links = links.clone();
664                            let link_ranges = link_ranges.clone();
665                            move |idx, _, cx| {
666                                for (ix, range) in link_ranges.iter().enumerate() {
667                                    if range.contains(&idx) {
668                                        return Some(LinkPreview::new(&links[ix].to_string(), cx));
669                                    }
670                                }
671                                None
672                            }
673                        })
674                        .on_click(
675                            link_ranges,
676                            move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
677                                Link::Web { url } => cx.open_url(url),
678                                Link::Path { path, .. } => {
679                                    if let Some(workspace) = &workspace {
680                                        _ = workspace.update(cx, |workspace, cx| {
681                                            workspace
682                                                .open_abs_path(
683                                                    path.clone(),
684                                                    OpenOptions {
685                                                        visible: Some(OpenVisible::None),
686                                                        ..Default::default()
687                                                    },
688                                                    window,
689                                                    cx,
690                                                )
691                                                .detach();
692                                        });
693                                    }
694                                }
695                            },
696                        ),
697                    )
698                    .into_any();
699                any_element.push(element);
700            }
701
702            MarkdownParagraphChunk::Image(image) => {
703                let image_resource = match image.link.clone() {
704                    Link::Web { url } => Resource::Uri(url.into()),
705                    Link::Path { path, .. } => Resource::Path(Arc::from(path)),
706                };
707
708                let element_id = cx.next_id(&image.source_range);
709
710                let image_element = div()
711                    .id(element_id)
712                    .cursor_pointer()
713                    .child(
714                        img(ImageSource::Resource(image_resource))
715                            .max_w_full()
716                            .with_fallback({
717                                let alt_text = image.alt_text.clone();
718                                move || div().children(alt_text.clone()).into_any_element()
719                            }),
720                    )
721                    .tooltip({
722                        let link = image.link.clone();
723                        move |_, cx| {
724                            InteractiveMarkdownElementTooltip::new(
725                                Some(link.to_string()),
726                                "open image",
727                                cx,
728                            )
729                            .into()
730                        }
731                    })
732                    .on_click({
733                        let workspace = workspace_clone.clone();
734                        let link = image.link.clone();
735                        move |_, window, cx| {
736                            if window.modifiers().secondary() {
737                                match &link {
738                                    Link::Web { url } => cx.open_url(url),
739                                    Link::Path { path, .. } => {
740                                        if let Some(workspace) = &workspace {
741                                            _ = workspace.update(cx, |workspace, cx| {
742                                                workspace
743                                                    .open_abs_path(
744                                                        path.clone(),
745                                                        OpenOptions {
746                                                            visible: Some(OpenVisible::None),
747                                                            ..Default::default()
748                                                        },
749                                                        window,
750                                                        cx,
751                                                    )
752                                                    .detach();
753                                            });
754                                        }
755                                    }
756                                }
757                            }
758                        }
759                    })
760                    .into_any();
761                any_element.push(image_element);
762            }
763        }
764    }
765
766    any_element
767}
768
769fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
770    let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
771    div().py(cx.scaled_rems(0.5)).child(rule).into_any()
772}
773
774struct InteractiveMarkdownElementTooltip {
775    tooltip_text: Option<SharedString>,
776    action_text: String,
777}
778
779impl InteractiveMarkdownElementTooltip {
780    pub fn new(tooltip_text: Option<String>, action_text: &str, cx: &mut App) -> Entity<Self> {
781        let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
782
783        cx.new(|_cx| Self {
784            tooltip_text,
785            action_text: action_text.to_string(),
786        })
787    }
788}
789
790impl Render for InteractiveMarkdownElementTooltip {
791    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
792        tooltip_container(window, cx, |el, _, _| {
793            let secondary_modifier = Keystroke {
794                modifiers: Modifiers::secondary_key(),
795                ..Default::default()
796            };
797
798            el.child(
799                v_flex()
800                    .gap_1()
801                    .when_some(self.tooltip_text.clone(), |this, text| {
802                        this.child(Label::new(text).size(LabelSize::Small))
803                    })
804                    .child(
805                        Label::new(format!(
806                            "{}-click to {}",
807                            secondary_modifier, self.action_text
808                        ))
809                        .size(LabelSize::Small)
810                        .color(Color::Muted),
811                    ),
812            )
813        })
814    }
815}