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