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