markdown_renderer.rs

  1use crate::markdown_elements::{
  2    HeadingLevel, Link, ParsedMarkdown, ParsedMarkdownBlockQuote, ParsedMarkdownCodeBlock,
  3    ParsedMarkdownElement, ParsedMarkdownHeading, ParsedMarkdownListItem,
  4    ParsedMarkdownListItemType, ParsedMarkdownTable, ParsedMarkdownTableAlignment,
  5    ParsedMarkdownTableRow, ParsedMarkdownText,
  6};
  7use gpui::{
  8    div, px, rems, AbsoluteLength, AnyElement, DefiniteLength, Div, Element, ElementId,
  9    HighlightStyle, Hsla, InteractiveText, IntoElement, Keystroke, Length, Modifiers,
 10    ParentElement, SharedString, Styled, StyledText, TextStyle, WeakView, WindowContext,
 11};
 12use settings::Settings;
 13use std::{
 14    ops::{Mul, Range},
 15    sync::Arc,
 16};
 17use theme::{ActiveTheme, SyntaxTheme, ThemeSettings};
 18use ui::{
 19    h_flex, relative, v_flex, Checkbox, FluentBuilder, InteractiveElement, LinkPreview, Selection,
 20    StatefulInteractiveElement, Tooltip,
 21};
 22use workspace::Workspace;
 23
 24type CheckboxClickedCallback = Arc<Box<dyn Fn(bool, Range<usize>, &mut WindowContext)>>;
 25
 26pub struct RenderContext {
 27    workspace: Option<WeakView<Workspace>>,
 28    next_id: usize,
 29    buffer_font_family: SharedString,
 30    buffer_text_style: TextStyle,
 31    text_style: TextStyle,
 32    border_color: Hsla,
 33    text_color: Hsla,
 34    text_muted_color: Hsla,
 35    code_block_background_color: Hsla,
 36    code_span_background_color: Hsla,
 37    syntax_theme: Arc<SyntaxTheme>,
 38    indent: usize,
 39    checkbox_clicked_callback: Option<CheckboxClickedCallback>,
 40}
 41
 42impl RenderContext {
 43    pub fn new(workspace: Option<WeakView<Workspace>>, cx: &WindowContext) -> RenderContext {
 44        let theme = cx.theme().clone();
 45
 46        let settings = ThemeSettings::get_global(cx);
 47        let buffer_font_family = settings.buffer_font.family.clone();
 48        let mut buffer_text_style = cx.text_style();
 49        buffer_text_style.font_family = buffer_font_family.clone();
 50
 51        RenderContext {
 52            workspace,
 53            next_id: 0,
 54            indent: 0,
 55            buffer_font_family,
 56            buffer_text_style,
 57            text_style: cx.text_style(),
 58            syntax_theme: theme.syntax().clone(),
 59            border_color: theme.colors().border,
 60            text_color: theme.colors().text,
 61            text_muted_color: theme.colors().text_muted,
 62            code_block_background_color: theme.colors().surface_background,
 63            code_span_background_color: theme.colors().editor_document_highlight_read_background,
 64            checkbox_clicked_callback: None,
 65        }
 66    }
 67
 68    pub fn with_checkbox_clicked_callback(
 69        mut self,
 70        callback: impl Fn(bool, Range<usize>, &mut WindowContext) + 'static,
 71    ) -> Self {
 72        self.checkbox_clicked_callback = Some(Arc::new(Box::new(callback)));
 73        self
 74    }
 75
 76    fn next_id(&mut self, span: &Range<usize>) -> ElementId {
 77        let id = format!("markdown-{}-{}-{}", self.next_id, span.start, span.end);
 78        self.next_id += 1;
 79        ElementId::from(SharedString::from(id))
 80    }
 81
 82    /// This ensures that children inside of block quotes
 83    /// have padding between them.
 84    ///
 85    /// For example, for this markdown:
 86    ///
 87    /// ```markdown
 88    /// > This is a block quote.
 89    /// >
 90    /// > And this is the next paragraph.
 91    /// ```
 92    ///
 93    /// We give padding between "This is a block quote."
 94    /// and "And this is the next paragraph."
 95    fn with_common_p(&self, element: Div) -> Div {
 96        if self.indent > 0 {
 97            element.pb_3()
 98        } else {
 99            element
100        }
101    }
102}
103
104pub fn render_parsed_markdown(
105    parsed: &ParsedMarkdown,
106    workspace: Option<WeakView<Workspace>>,
107    cx: &WindowContext,
108) -> Vec<AnyElement> {
109    let mut cx = RenderContext::new(workspace, cx);
110    let mut elements = Vec::new();
111
112    for child in &parsed.children {
113        elements.push(render_markdown_block(child, &mut cx));
114    }
115
116    elements
117}
118
119pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
120    use ParsedMarkdownElement::*;
121    match block {
122        Paragraph(text) => render_markdown_paragraph(text, cx),
123        Heading(heading) => render_markdown_heading(heading, cx),
124        ListItem(list_item) => render_markdown_list_item(list_item, cx),
125        Table(table) => render_markdown_table(table, cx),
126        BlockQuote(block_quote) => render_markdown_block_quote(block_quote, cx),
127        CodeBlock(code_block) => render_markdown_code_block(code_block, cx),
128        HorizontalRule(_) => render_markdown_rule(cx),
129    }
130}
131
132fn render_markdown_heading(parsed: &ParsedMarkdownHeading, cx: &mut RenderContext) -> AnyElement {
133    let size = match parsed.level {
134        HeadingLevel::H1 => rems(2.),
135        HeadingLevel::H2 => rems(1.5),
136        HeadingLevel::H3 => rems(1.25),
137        HeadingLevel::H4 => rems(1.),
138        HeadingLevel::H5 => rems(0.875),
139        HeadingLevel::H6 => rems(0.85),
140    };
141
142    let color = match parsed.level {
143        HeadingLevel::H6 => cx.text_muted_color,
144        _ => cx.text_color,
145    };
146
147    let line_height = DefiniteLength::from(size.mul(1.25));
148
149    div()
150        .line_height(line_height)
151        .text_size(size)
152        .text_color(color)
153        .pt(rems(0.15))
154        .pb_1()
155        .child(render_markdown_text(&parsed.contents, cx))
156        .whitespace_normal()
157        .into_any()
158}
159
160fn render_markdown_list_item(
161    parsed: &ParsedMarkdownListItem,
162    cx: &mut RenderContext,
163) -> AnyElement {
164    use ParsedMarkdownListItemType::*;
165
166    let padding = rems((parsed.depth - 1) as f32);
167
168    let bullet = match &parsed.item_type {
169        Ordered(order) => format!("{}.", order).into_any_element(),
170        Unordered => "".into_any_element(),
171        Task(checked, range) => div()
172            .id(cx.next_id(range))
173            .mt(px(3.))
174            .child(
175                Checkbox::new(
176                    "checkbox",
177                    if *checked {
178                        Selection::Selected
179                    } else {
180                        Selection::Unselected
181                    },
182                )
183                .when_some(
184                    cx.checkbox_clicked_callback.clone(),
185                    |this, callback| {
186                        this.on_click({
187                            let range = range.clone();
188                            move |selection, cx| {
189                                let checked = match selection {
190                                    Selection::Selected => true,
191                                    Selection::Unselected => false,
192                                    _ => return,
193                                };
194
195                                if cx.modifiers().secondary() {
196                                    callback(checked, range.clone(), cx);
197                                }
198                            }
199                        })
200                    },
201                ),
202            )
203            .hover(|s| s.cursor_pointer())
204            .tooltip(|cx| {
205                let secondary_modifier = Keystroke {
206                    key: "".to_string(),
207                    modifiers: Modifiers::secondary_key(),
208                    ime_key: None,
209                };
210                Tooltip::text(
211                    format!("{}-click to toggle the checkbox", secondary_modifier),
212                    cx,
213                )
214            })
215            .into_any_element(),
216    };
217    let bullet = div().mr_2().child(bullet);
218
219    let contents: Vec<AnyElement> = parsed
220        .content
221        .iter()
222        .map(|c| render_markdown_block(c, cx))
223        .collect();
224
225    let item = h_flex()
226        .pl(DefiniteLength::Absolute(AbsoluteLength::Rems(padding)))
227        .items_start()
228        .children(vec![bullet, div().children(contents).pr_4().w_full()]);
229
230    cx.with_common_p(item).into_any()
231}
232
233fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
234    let mut max_lengths: Vec<usize> = vec![0; parsed.header.children.len()];
235
236    for (index, cell) in parsed.header.children.iter().enumerate() {
237        let length = cell.contents.len();
238        max_lengths[index] = length;
239    }
240
241    for row in &parsed.body {
242        for (index, cell) in row.children.iter().enumerate() {
243            let length = cell.contents.len();
244            if length > max_lengths[index] {
245                max_lengths[index] = length;
246            }
247        }
248    }
249
250    let total_max_length: usize = max_lengths.iter().sum();
251    let max_column_widths: Vec<f32> = max_lengths
252        .iter()
253        .map(|&length| length as f32 / total_max_length as f32)
254        .collect();
255
256    let header = render_markdown_table_row(
257        &parsed.header,
258        &parsed.column_alignments,
259        &max_column_widths,
260        true,
261        cx,
262    );
263
264    let body: Vec<AnyElement> = parsed
265        .body
266        .iter()
267        .map(|row| {
268            render_markdown_table_row(
269                row,
270                &parsed.column_alignments,
271                &max_column_widths,
272                false,
273                cx,
274            )
275        })
276        .collect();
277
278    cx.with_common_p(v_flex())
279        .w_full()
280        .child(header)
281        .children(body)
282        .into_any()
283}
284
285fn render_markdown_table_row(
286    parsed: &ParsedMarkdownTableRow,
287    alignments: &Vec<ParsedMarkdownTableAlignment>,
288    max_column_widths: &Vec<f32>,
289    is_header: bool,
290    cx: &mut RenderContext,
291) -> AnyElement {
292    let mut items = vec![];
293
294    for (index, cell) in parsed.children.iter().enumerate() {
295        let alignment = alignments
296            .get(index)
297            .copied()
298            .unwrap_or(ParsedMarkdownTableAlignment::None);
299
300        let contents = render_markdown_text(cell, cx);
301
302        let container = match alignment {
303            ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
304            ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
305            ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
306        };
307
308        let max_width = max_column_widths.get(index).unwrap_or(&0.0);
309
310        let mut cell = container
311            .w(Length::Definite(relative(*max_width)))
312            .h_full()
313            .child(contents)
314            .px_2()
315            .py_1()
316            .border_color(cx.border_color);
317
318        if is_header {
319            cell = cell.border_2()
320        } else {
321            cell = cell.border_1()
322        }
323
324        items.push(cell);
325    }
326
327    h_flex().children(items).into_any_element()
328}
329
330fn render_markdown_block_quote(
331    parsed: &ParsedMarkdownBlockQuote,
332    cx: &mut RenderContext,
333) -> AnyElement {
334    cx.indent += 1;
335
336    let children: Vec<AnyElement> = parsed
337        .children
338        .iter()
339        .map(|child| render_markdown_block(child, cx))
340        .collect();
341
342    cx.indent -= 1;
343
344    cx.with_common_p(div())
345        .child(
346            div()
347                .border_l_4()
348                .border_color(cx.border_color)
349                .pl_3()
350                .children(children),
351        )
352        .into_any()
353}
354
355fn render_markdown_code_block(
356    parsed: &ParsedMarkdownCodeBlock,
357    cx: &mut RenderContext,
358) -> AnyElement {
359    let body = if let Some(highlights) = parsed.highlights.as_ref() {
360        StyledText::new(parsed.contents.clone()).with_highlights(
361            &cx.buffer_text_style,
362            highlights.iter().filter_map(|(range, highlight_id)| {
363                highlight_id
364                    .style(cx.syntax_theme.as_ref())
365                    .map(|style| (range.clone(), style))
366            }),
367        )
368    } else {
369        StyledText::new(parsed.contents.clone())
370    };
371
372    cx.with_common_p(div())
373        .font_family(cx.buffer_font_family.clone())
374        .px_3()
375        .py_3()
376        .bg(cx.code_block_background_color)
377        .rounded_md()
378        .child(body)
379        .into_any()
380}
381
382fn render_markdown_paragraph(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
383    cx.with_common_p(div())
384        .child(render_markdown_text(parsed, cx))
385        .into_any_element()
386}
387
388fn render_markdown_text(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
389    let element_id = cx.next_id(&parsed.source_range);
390
391    let highlights = gpui::combine_highlights(
392        parsed.highlights.iter().filter_map(|(range, highlight)| {
393            let highlight = highlight.to_highlight_style(&cx.syntax_theme)?;
394            Some((range.clone(), highlight))
395        }),
396        parsed
397            .regions
398            .iter()
399            .zip(&parsed.region_ranges)
400            .filter_map(|(region, range)| {
401                if region.code {
402                    Some((
403                        range.clone(),
404                        HighlightStyle {
405                            background_color: Some(cx.code_span_background_color),
406                            ..Default::default()
407                        },
408                    ))
409                } else {
410                    None
411                }
412            }),
413    );
414
415    let mut links = Vec::new();
416    let mut link_ranges = Vec::new();
417    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
418        if let Some(link) = region.link.clone() {
419            links.push(link);
420            link_ranges.push(range.clone());
421        }
422    }
423
424    let workspace = cx.workspace.clone();
425
426    InteractiveText::new(
427        element_id,
428        StyledText::new(parsed.contents.clone()).with_highlights(&cx.text_style, highlights),
429    )
430    .tooltip({
431        let links = links.clone();
432        let link_ranges = link_ranges.clone();
433        move |idx, cx| {
434            for (ix, range) in link_ranges.iter().enumerate() {
435                if range.contains(&idx) {
436                    return Some(LinkPreview::new(&links[ix].to_string(), cx));
437                }
438            }
439            None
440        }
441    })
442    .on_click(
443        link_ranges,
444        move |clicked_range_ix, window_cx| match &links[clicked_range_ix] {
445            Link::Web { url } => window_cx.open_url(url),
446            Link::Path {
447                path,
448                display_path: _,
449            } => {
450                if let Some(workspace) = &workspace {
451                    _ = workspace.update(window_cx, |workspace, cx| {
452                        workspace.open_abs_path(path.clone(), false, cx).detach();
453                    });
454                }
455            }
456        },
457    )
458    .into_any_element()
459}
460
461fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
462    let rule = div().w_full().h(px(2.)).bg(cx.border_color);
463    div().pt_3().pb_3().child(rule).into_any()
464}