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    element_background_color: Hsla,
 55    text_color: Hsla,
 56    link_color: Hsla,
 57    window_rem_size: Pixels,
 58    text_muted_color: Hsla,
 59    code_block_background_color: Hsla,
 60    code_span_background_color: Hsla,
 61    syntax_theme: Arc<SyntaxTheme>,
 62    indent: usize,
 63    checkbox_clicked_callback: Option<CheckboxClickedCallback>,
 64    is_last_child: bool,
 65}
 66
 67impl RenderContext {
 68    pub fn new(
 69        workspace: Option<WeakEntity<Workspace>>,
 70        window: &mut Window,
 71        cx: &mut App,
 72    ) -> RenderContext {
 73        let theme = cx.theme().clone();
 74
 75        let settings = ThemeSettings::get_global(cx);
 76        let buffer_font_family = settings.buffer_font.family.clone();
 77        let mut buffer_text_style = window.text_style();
 78        buffer_text_style.font_family = buffer_font_family.clone();
 79        buffer_text_style.font_size = AbsoluteLength::from(settings.buffer_font_size(cx));
 80
 81        RenderContext {
 82            workspace,
 83            next_id: 0,
 84            indent: 0,
 85            buffer_font_family,
 86            buffer_text_style,
 87            text_style: window.text_style(),
 88            syntax_theme: theme.syntax().clone(),
 89            border_color: theme.colors().border,
 90            element_background_color: theme.colors().element_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        cx,
515    );
516
517    let body: Vec<AnyElement> = parsed
518        .body
519        .iter()
520        .map(|row| {
521            render_markdown_table_row(
522                row,
523                &parsed.column_alignments,
524                &max_column_widths,
525                false,
526                cx,
527            )
528        })
529        .collect();
530
531    cx.with_common_p(v_flex())
532        .w_full()
533        .child(header)
534        .children(body)
535        .into_any()
536}
537
538fn render_markdown_table_row(
539    parsed: &ParsedMarkdownTableRow,
540    alignments: &Vec<ParsedMarkdownTableAlignment>,
541    max_column_widths: &Vec<f32>,
542    is_header: bool,
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.element_background_color)
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    row.children(items).into_any_element()
592}
593
594fn render_markdown_block_quote(
595    parsed: &ParsedMarkdownBlockQuote,
596    cx: &mut RenderContext,
597) -> AnyElement {
598    cx.indent += 1;
599
600    let children: Vec<AnyElement> = parsed
601        .children
602        .iter()
603        .enumerate()
604        .map(|(ix, child)| {
605            cx.with_last_child(ix + 1 == parsed.children.len(), |cx| {
606                render_markdown_block(child, cx)
607            })
608        })
609        .collect();
610
611    cx.indent -= 1;
612
613    cx.with_common_p(div())
614        .child(
615            div()
616                .border_l_4()
617                .border_color(cx.border_color)
618                .pl_3()
619                .children(children),
620        )
621        .into_any()
622}
623
624fn render_markdown_code_block(
625    parsed: &ParsedMarkdownCodeBlock,
626    cx: &mut RenderContext,
627) -> AnyElement {
628    let body = if let Some(highlights) = parsed.highlights.as_ref() {
629        StyledText::new(parsed.contents.clone()).with_default_highlights(
630            &cx.buffer_text_style,
631            highlights.iter().filter_map(|(range, highlight_id)| {
632                highlight_id
633                    .style(cx.syntax_theme.as_ref())
634                    .map(|style| (range.clone(), style))
635            }),
636        )
637    } else {
638        StyledText::new(parsed.contents.clone())
639    };
640
641    let copy_block_button = IconButton::new("copy-code", IconName::Copy)
642        .icon_size(IconSize::Small)
643        .on_click({
644            let contents = parsed.contents.clone();
645            move |_, _window, cx| {
646                cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
647            }
648        })
649        .tooltip(Tooltip::text("Copy code block"))
650        .visible_on_hover("markdown-block");
651
652    cx.with_common_p(div())
653        .font_family(cx.buffer_font_family.clone())
654        .px_3()
655        .py_3()
656        .bg(cx.code_block_background_color)
657        .rounded_sm()
658        .child(body)
659        .child(
660            div()
661                .h_flex()
662                .absolute()
663                .right_1()
664                .top_1()
665                .child(copy_block_button),
666        )
667        .into_any()
668}
669
670fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
671    cx.with_common_p(div())
672        .children(render_markdown_text(parsed, cx))
673        .flex()
674        .flex_col()
675        .into_any_element()
676}
677
678fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
679    let mut any_element = Vec::with_capacity(parsed_new.len());
680    // these values are cloned in-order satisfy borrow checker
681    let syntax_theme = cx.syntax_theme.clone();
682    let workspace_clone = cx.workspace.clone();
683    let code_span_bg_color = cx.code_span_background_color;
684    let text_style = cx.text_style.clone();
685    let link_color = cx.link_color;
686
687    for parsed_region in parsed_new {
688        match parsed_region {
689            MarkdownParagraphChunk::Text(parsed) => {
690                let element_id = cx.next_id(&parsed.source_range);
691
692                let highlights = gpui::combine_highlights(
693                    parsed.highlights.iter().filter_map(|(range, highlight)| {
694                        highlight
695                            .to_highlight_style(&syntax_theme, link_color)
696                            .map(|style| (range.clone(), style))
697                    }),
698                    parsed.regions.iter().zip(&parsed.region_ranges).filter_map(
699                        |(region, range)| {
700                            if region.code {
701                                Some((
702                                    range.clone(),
703                                    HighlightStyle {
704                                        background_color: Some(code_span_bg_color),
705                                        ..Default::default()
706                                    },
707                                ))
708                            } else {
709                                None
710                            }
711                        },
712                    ),
713                );
714                let mut links = Vec::new();
715                let mut link_ranges = Vec::new();
716                for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
717                    if let Some(link) = region.link.clone() {
718                        links.push(link);
719                        link_ranges.push(range.clone());
720                    }
721                }
722                let workspace = workspace_clone.clone();
723                let element = div()
724                    .child(
725                        InteractiveText::new(
726                            element_id,
727                            StyledText::new(parsed.contents.clone())
728                                .with_default_highlights(&text_style, highlights),
729                        )
730                        .tooltip({
731                            let links = links.clone();
732                            let link_ranges = link_ranges.clone();
733                            move |idx, _, cx| {
734                                for (ix, range) in link_ranges.iter().enumerate() {
735                                    if range.contains(&idx) {
736                                        return Some(LinkPreview::new(&links[ix].to_string(), cx));
737                                    }
738                                }
739                                None
740                            }
741                        })
742                        .on_click(
743                            link_ranges,
744                            move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
745                                Link::Web { url } => cx.open_url(url),
746                                Link::Path { path, .. } => {
747                                    if let Some(workspace) = &workspace {
748                                        _ = workspace.update(cx, |workspace, cx| {
749                                            workspace
750                                                .open_abs_path(
751                                                    normalize_path(path.clone().as_path()),
752                                                    OpenOptions {
753                                                        visible: Some(OpenVisible::None),
754                                                        ..Default::default()
755                                                    },
756                                                    window,
757                                                    cx,
758                                                )
759                                                .detach();
760                                        });
761                                    }
762                                }
763                            },
764                        ),
765                    )
766                    .into_any();
767                any_element.push(element);
768            }
769
770            MarkdownParagraphChunk::Image(image) => {
771                any_element.push(render_markdown_image(image, cx));
772            }
773        }
774    }
775
776    any_element
777}
778
779fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
780    let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
781    div().py(cx.scaled_rems(0.5)).child(rule).into_any()
782}
783
784fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
785    let image_resource = match image.link.clone() {
786        Link::Web { url } => Resource::Uri(url.into()),
787        Link::Path { path, .. } => Resource::Path(Arc::from(path)),
788    };
789
790    let element_id = cx.next_id(&image.source_range);
791    let workspace = cx.workspace.clone();
792
793    div()
794        .id(element_id)
795        .cursor_pointer()
796        .child(
797            img(ImageSource::Resource(image_resource))
798                .max_w_full()
799                .with_fallback({
800                    let alt_text = image.alt_text.clone();
801                    move || div().children(alt_text.clone()).into_any_element()
802                })
803                .when_some(image.height, |this, height| this.h(height))
804                .when_some(image.width, |this, width| this.w(width)),
805        )
806        .tooltip({
807            let link = image.link.clone();
808            let alt_text = image.alt_text.clone();
809            move |_, cx| {
810                InteractiveMarkdownElementTooltip::new(
811                    Some(alt_text.clone().unwrap_or(link.to_string().into())),
812                    "open image",
813                    cx,
814                )
815                .into()
816            }
817        })
818        .on_click({
819            let link = image.link.clone();
820            move |_, window, cx| {
821                if window.modifiers().secondary() {
822                    match &link {
823                        Link::Web { url } => cx.open_url(url),
824                        Link::Path { path, .. } => {
825                            if let Some(workspace) = &workspace {
826                                _ = workspace.update(cx, |workspace, cx| {
827                                    workspace
828                                        .open_abs_path(
829                                            path.clone(),
830                                            OpenOptions {
831                                                visible: Some(OpenVisible::None),
832                                                ..Default::default()
833                                            },
834                                            window,
835                                            cx,
836                                        )
837                                        .detach();
838                                });
839                            }
840                        }
841                    }
842                }
843            }
844        })
845        .into_any()
846}
847
848struct InteractiveMarkdownElementTooltip {
849    tooltip_text: Option<SharedString>,
850    action_text: SharedString,
851}
852
853impl InteractiveMarkdownElementTooltip {
854    pub fn new(
855        tooltip_text: Option<SharedString>,
856        action_text: impl Into<SharedString>,
857        cx: &mut App,
858    ) -> Entity<Self> {
859        let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
860
861        cx.new(|_cx| Self {
862            tooltip_text,
863            action_text: action_text.into(),
864        })
865    }
866}
867
868impl Render for InteractiveMarkdownElementTooltip {
869    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
870        tooltip_container(cx, |el, _| {
871            let secondary_modifier = Keystroke {
872                modifiers: Modifiers::secondary_key(),
873                ..Default::default()
874            };
875
876            el.child(
877                v_flex()
878                    .gap_1()
879                    .when_some(self.tooltip_text.clone(), |this, text| {
880                        this.child(Label::new(text).size(LabelSize::Small))
881                    })
882                    .child(
883                        Label::new(format!(
884                            "{}-click to {}",
885                            secondary_modifier, self.action_text
886                        ))
887                        .size(LabelSize::Small)
888                        .color(Color::Muted),
889                    ),
890            )
891        })
892    }
893}