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            div().children(contents).pr(cx.scaled_rems(1.0)).w_full(),
281        ]);
282
283    cx.with_common_p(item).into_any()
284}
285
286/// # MarkdownCheckbox ///
287/// HACK: Copied from `ui/src/components/toggle.rs` to deal with scaling issues in markdown preview
288/// changes should be integrated into `Checkbox` in `toggle.rs` while making sure checkboxes elsewhere in the
289/// app are not visually affected
290#[derive(gpui::IntoElement)]
291struct MarkdownCheckbox {
292    id: ElementId,
293    toggle_state: ToggleState,
294    disabled: bool,
295    placeholder: bool,
296    on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
297    filled: bool,
298    style: ui::ToggleStyle,
299    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
300    label: Option<SharedString>,
301    render_cx: RenderContext,
302}
303
304impl MarkdownCheckbox {
305    /// Creates a new [`Checkbox`].
306    fn new(id: impl Into<ElementId>, checked: ToggleState, render_cx: RenderContext) -> Self {
307        Self {
308            id: id.into(),
309            toggle_state: checked,
310            disabled: false,
311            on_click: None,
312            filled: false,
313            style: ui::ToggleStyle::default(),
314            tooltip: None,
315            label: None,
316            placeholder: false,
317            render_cx,
318        }
319    }
320
321    /// Binds a handler to the [`Checkbox`] that will be called when clicked.
322    fn on_click(mut self, handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static) -> Self {
323        self.on_click = Some(Box::new(handler));
324        self
325    }
326
327    fn bg_color(&self, cx: &App) -> Hsla {
328        let style = self.style.clone();
329        match (style, self.filled) {
330            (ui::ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
331            (ui::ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
332            (ui::ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
333            (ui::ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
334            (ui::ToggleStyle::Custom(_), false) => gpui::transparent_black(),
335            (ui::ToggleStyle::Custom(color), true) => color.opacity(0.2),
336        }
337    }
338
339    fn border_color(&self, cx: &App) -> Hsla {
340        if self.disabled {
341            return cx.theme().colors().border_variant;
342        }
343
344        match self.style.clone() {
345            ui::ToggleStyle::Ghost => cx.theme().colors().border,
346            ui::ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
347            ui::ToggleStyle::Custom(color) => color.opacity(0.3),
348        }
349    }
350}
351
352impl gpui::RenderOnce for MarkdownCheckbox {
353    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
354        let group_id = format!("checkbox_group_{:?}", self.id);
355        let color = if self.disabled {
356            Color::Disabled
357        } else {
358            Color::Selected
359        };
360        let icon_size_small = IconSize::Custom(self.render_cx.scaled_rems(14. / 16.)); // was IconSize::Small
361        let icon = match self.toggle_state {
362            ToggleState::Selected => {
363                if self.placeholder {
364                    None
365                } else {
366                    Some(
367                        ui::Icon::new(IconName::Check)
368                            .size(icon_size_small)
369                            .color(color),
370                    )
371                }
372            }
373            ToggleState::Indeterminate => Some(
374                ui::Icon::new(IconName::Dash)
375                    .size(icon_size_small)
376                    .color(color),
377            ),
378            ToggleState::Unselected => None,
379        };
380
381        let bg_color = self.bg_color(cx);
382        let border_color = self.border_color(cx);
383        let hover_border_color = border_color.alpha(0.7);
384
385        let size = self.render_cx.scaled_rems(1.25); // was Self::container_size(); (20px)
386
387        let checkbox = h_flex()
388            .id(self.id.clone())
389            .justify_center()
390            .items_center()
391            .size(size)
392            .group(group_id.clone())
393            .child(
394                div()
395                    .flex()
396                    .flex_none()
397                    .justify_center()
398                    .items_center()
399                    .m(self.render_cx.scaled_rems(0.25)) // was .m_1
400                    .size(self.render_cx.scaled_rems(1.0)) // was .size_4
401                    .rounded(self.render_cx.scaled_rems(0.125)) // was .rounded_xs
402                    .border_1()
403                    .bg(bg_color)
404                    .border_color(border_color)
405                    .when(self.disabled, |this| this.cursor_not_allowed())
406                    .when(self.disabled, |this| {
407                        this.bg(cx.theme().colors().element_disabled.opacity(0.6))
408                    })
409                    .when(!self.disabled, |this| {
410                        this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
411                    })
412                    .when(self.placeholder, |this| {
413                        this.child(
414                            div()
415                                .flex_none()
416                                .rounded_full()
417                                .bg(color.color(cx).alpha(0.5))
418                                .size(self.render_cx.scaled_rems(0.25)), // was .size_1
419                        )
420                    })
421                    .children(icon),
422            );
423
424        h_flex()
425            .id(self.id)
426            .gap(ui::DynamicSpacing::Base06.rems(cx))
427            .child(checkbox)
428            .when_some(
429                self.on_click.filter(|_| !self.disabled),
430                |this, on_click| {
431                    this.on_click(move |_, window, cx| {
432                        on_click(&self.toggle_state.inverse(), window, cx)
433                    })
434                },
435            )
436            // TODO: Allow label size to be different from default.
437            // TODO: Allow label color to be different from muted.
438            .when_some(self.label, |this, label| {
439                this.child(Label::new(label).color(Color::Muted))
440            })
441            .when_some(self.tooltip, |this, tooltip| {
442                this.tooltip(move |window, cx| tooltip(window, cx))
443            })
444    }
445}
446
447fn paragraph_len(paragraphs: &MarkdownParagraph) -> usize {
448    paragraphs
449        .iter()
450        .map(|paragraph| match paragraph {
451            MarkdownParagraphChunk::Text(text) => text.contents.len(),
452            // TODO: Scale column width based on image size
453            MarkdownParagraphChunk::Image(_) => 1,
454        })
455        .sum()
456}
457
458fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
459    let mut max_lengths: Vec<usize> = vec![0; parsed.header.children.len()];
460
461    for (index, cell) in parsed.header.children.iter().enumerate() {
462        let length = paragraph_len(cell);
463        max_lengths[index] = length;
464    }
465
466    for row in &parsed.body {
467        for (index, cell) in row.children.iter().enumerate() {
468            let length = paragraph_len(cell);
469
470            if length > max_lengths[index] {
471                max_lengths[index] = length;
472            }
473        }
474    }
475
476    let total_max_length: usize = max_lengths.iter().sum();
477    let max_column_widths: Vec<f32> = max_lengths
478        .iter()
479        .map(|&length| length as f32 / total_max_length as f32)
480        .collect();
481
482    let header = render_markdown_table_row(
483        &parsed.header,
484        &parsed.column_alignments,
485        &max_column_widths,
486        true,
487        cx,
488    );
489
490    let body: Vec<AnyElement> = parsed
491        .body
492        .iter()
493        .map(|row| {
494            render_markdown_table_row(
495                row,
496                &parsed.column_alignments,
497                &max_column_widths,
498                false,
499                cx,
500            )
501        })
502        .collect();
503
504    cx.with_common_p(v_flex())
505        .w_full()
506        .child(header)
507        .children(body)
508        .into_any()
509}
510
511fn render_markdown_table_row(
512    parsed: &ParsedMarkdownTableRow,
513    alignments: &Vec<ParsedMarkdownTableAlignment>,
514    max_column_widths: &Vec<f32>,
515    is_header: bool,
516    cx: &mut RenderContext,
517) -> AnyElement {
518    let mut items = vec![];
519
520    for (index, cell) in parsed.children.iter().enumerate() {
521        let alignment = alignments
522            .get(index)
523            .copied()
524            .unwrap_or(ParsedMarkdownTableAlignment::None);
525
526        let contents = render_markdown_text(cell, cx);
527
528        let container = match alignment {
529            ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
530            ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
531            ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
532        };
533
534        let max_width = max_column_widths.get(index).unwrap_or(&0.0);
535        let mut cell = container
536            .w(Length::Definite(relative(*max_width)))
537            .h_full()
538            .children(contents)
539            .px_2()
540            .py_1()
541            .border_color(cx.border_color);
542
543        if is_header {
544            cell = cell.border_2()
545        } else {
546            cell = cell.border_1()
547        }
548
549        items.push(cell);
550    }
551
552    h_flex().children(items).into_any_element()
553}
554
555fn render_markdown_block_quote(
556    parsed: &ParsedMarkdownBlockQuote,
557    cx: &mut RenderContext,
558) -> AnyElement {
559    cx.indent += 1;
560
561    let children: Vec<AnyElement> = parsed
562        .children
563        .iter()
564        .map(|child| render_markdown_block(child, cx))
565        .collect();
566
567    cx.indent -= 1;
568
569    cx.with_common_p(div())
570        .child(
571            div()
572                .border_l_4()
573                .border_color(cx.border_color)
574                .pl_3()
575                .children(children),
576        )
577        .into_any()
578}
579
580fn render_markdown_code_block(
581    parsed: &ParsedMarkdownCodeBlock,
582    cx: &mut RenderContext,
583) -> AnyElement {
584    let body = if let Some(highlights) = parsed.highlights.as_ref() {
585        StyledText::new(parsed.contents.clone()).with_default_highlights(
586            &cx.buffer_text_style,
587            highlights.iter().filter_map(|(range, highlight_id)| {
588                highlight_id
589                    .style(cx.syntax_theme.as_ref())
590                    .map(|style| (range.clone(), style))
591            }),
592        )
593    } else {
594        StyledText::new(parsed.contents.clone())
595    };
596
597    let copy_block_button = IconButton::new("copy-code", IconName::Copy)
598        .icon_size(IconSize::Small)
599        .on_click({
600            let contents = parsed.contents.clone();
601            move |_, _window, cx| {
602                cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
603            }
604        })
605        .tooltip(Tooltip::text("Copy code block"))
606        .visible_on_hover("markdown-block");
607
608    cx.with_common_p(div())
609        .font_family(cx.buffer_font_family.clone())
610        .px_3()
611        .py_3()
612        .bg(cx.code_block_background_color)
613        .rounded_sm()
614        .child(body)
615        .child(
616            div()
617                .h_flex()
618                .absolute()
619                .right_1()
620                .top_1()
621                .child(copy_block_button),
622        )
623        .into_any()
624}
625
626fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
627    cx.with_common_p(h_flex().flex_wrap())
628        .children(render_markdown_text(parsed, cx))
629        .into_any_element()
630}
631
632fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
633    let mut any_element = Vec::with_capacity(parsed_new.len());
634    // these values are cloned in-order satisfy borrow checker
635    let syntax_theme = cx.syntax_theme.clone();
636    let workspace_clone = cx.workspace.clone();
637    let code_span_bg_color = cx.code_span_background_color;
638    let text_style = cx.text_style.clone();
639
640    for parsed_region in parsed_new {
641        match parsed_region {
642            MarkdownParagraphChunk::Text(parsed) => {
643                let element_id = cx.next_id(&parsed.source_range);
644
645                let highlights = gpui::combine_highlights(
646                    parsed.highlights.iter().filter_map(|(range, highlight)| {
647                        highlight
648                            .to_highlight_style(&syntax_theme)
649                            .map(|style| (range.clone(), style))
650                    }),
651                    parsed.regions.iter().zip(&parsed.region_ranges).filter_map(
652                        |(region, range)| {
653                            if region.code {
654                                Some((
655                                    range.clone(),
656                                    HighlightStyle {
657                                        background_color: Some(code_span_bg_color),
658                                        ..Default::default()
659                                    },
660                                ))
661                            } else {
662                                None
663                            }
664                        },
665                    ),
666                );
667                let mut links = Vec::new();
668                let mut link_ranges = Vec::new();
669                for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
670                    if let Some(link) = region.link.clone() {
671                        links.push(link);
672                        link_ranges.push(range.clone());
673                    }
674                }
675                let workspace = workspace_clone.clone();
676                let element = div()
677                    .child(
678                        InteractiveText::new(
679                            element_id,
680                            StyledText::new(parsed.contents.clone())
681                                .with_default_highlights(&text_style, highlights),
682                        )
683                        .tooltip({
684                            let links = links.clone();
685                            let link_ranges = link_ranges.clone();
686                            move |idx, _, cx| {
687                                for (ix, range) in link_ranges.iter().enumerate() {
688                                    if range.contains(&idx) {
689                                        return Some(LinkPreview::new(&links[ix].to_string(), cx));
690                                    }
691                                }
692                                None
693                            }
694                        })
695                        .on_click(
696                            link_ranges,
697                            move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
698                                Link::Web { url } => cx.open_url(url),
699                                Link::Path { path, .. } => {
700                                    if let Some(workspace) = &workspace {
701                                        _ = workspace.update(cx, |workspace, cx| {
702                                            workspace
703                                                .open_abs_path(
704                                                    normalize_path(path.clone().as_path()),
705                                                    OpenOptions {
706                                                        visible: Some(OpenVisible::None),
707                                                        ..Default::default()
708                                                    },
709                                                    window,
710                                                    cx,
711                                                )
712                                                .detach();
713                                        });
714                                    }
715                                }
716                            },
717                        ),
718                    )
719                    .into_any();
720                any_element.push(element);
721            }
722
723            MarkdownParagraphChunk::Image(image) => {
724                any_element.push(render_markdown_image(image, cx));
725            }
726        }
727    }
728
729    any_element
730}
731
732fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
733    let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
734    div().py(cx.scaled_rems(0.5)).child(rule).into_any()
735}
736
737fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
738    let image_resource = match image.link.clone() {
739        Link::Web { url } => Resource::Uri(url.into()),
740        Link::Path { path, .. } => Resource::Path(Arc::from(path)),
741    };
742
743    let element_id = cx.next_id(&image.source_range);
744    let workspace = cx.workspace.clone();
745
746    div()
747        .id(element_id)
748        .cursor_pointer()
749        .child(
750            img(ImageSource::Resource(image_resource))
751                .max_w_full()
752                .with_fallback({
753                    let alt_text = image.alt_text.clone();
754                    move || div().children(alt_text.clone()).into_any_element()
755                })
756                .when_some(image.height, |this, height| this.h(height))
757                .when_some(image.width, |this, width| this.w(width)),
758        )
759        .tooltip({
760            let link = image.link.clone();
761            let alt_text = image.alt_text.clone();
762            move |_, cx| {
763                InteractiveMarkdownElementTooltip::new(
764                    Some(alt_text.clone().unwrap_or(link.to_string().into())),
765                    "open image",
766                    cx,
767                )
768                .into()
769            }
770        })
771        .on_click({
772            let link = image.link.clone();
773            move |_, window, cx| {
774                if window.modifiers().secondary() {
775                    match &link {
776                        Link::Web { url } => cx.open_url(url),
777                        Link::Path { path, .. } => {
778                            if let Some(workspace) = &workspace {
779                                _ = workspace.update(cx, |workspace, cx| {
780                                    workspace
781                                        .open_abs_path(
782                                            path.clone(),
783                                            OpenOptions {
784                                                visible: Some(OpenVisible::None),
785                                                ..Default::default()
786                                            },
787                                            window,
788                                            cx,
789                                        )
790                                        .detach();
791                                });
792                            }
793                        }
794                    }
795                }
796            }
797        })
798        .into_any()
799}
800
801struct InteractiveMarkdownElementTooltip {
802    tooltip_text: Option<SharedString>,
803    action_text: SharedString,
804}
805
806impl InteractiveMarkdownElementTooltip {
807    pub fn new(
808        tooltip_text: Option<SharedString>,
809        action_text: impl Into<SharedString>,
810        cx: &mut App,
811    ) -> Entity<Self> {
812        let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
813
814        cx.new(|_cx| Self {
815            tooltip_text,
816            action_text: action_text.into(),
817        })
818    }
819}
820
821impl Render for InteractiveMarkdownElementTooltip {
822    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
823        tooltip_container(window, cx, |el, _, _| {
824            let secondary_modifier = Keystroke {
825                modifiers: Modifiers::secondary_key(),
826                ..Default::default()
827            };
828
829            el.child(
830                v_flex()
831                    .gap_1()
832                    .when_some(self.tooltip_text.clone(), |this, text| {
833                        this.child(Label::new(text).size(LabelSize::Small))
834                    })
835                    .child(
836                        Label::new(format!(
837                            "{}-click to {}",
838                            secondary_modifier, self.action_text
839                        ))
840                        .size(LabelSize::Small)
841                        .color(Color::Muted),
842                    ),
843            )
844        })
845    }
846}