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