markdown_renderer.rs

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