markdown_renderer.rs

  1use crate::markdown_elements::{
  2    HeadingLevel, Link, ParsedMarkdown, ParsedMarkdownBlockQuote, ParsedMarkdownCodeBlock,
  3    ParsedMarkdownElement, ParsedMarkdownHeading, ParsedMarkdownList, ParsedMarkdownListItemType,
  4    ParsedMarkdownTable, ParsedMarkdownTableAlignment, ParsedMarkdownTableRow, ParsedMarkdownText,
  5};
  6use gpui::{
  7    div, px, rems, AbsoluteLength, AnyElement, DefiniteLength, Div, Element, ElementId,
  8    HighlightStyle, Hsla, InteractiveText, IntoElement, ParentElement, SharedString, Styled,
  9    StyledText, TextStyle, WeakView, WindowContext,
 10};
 11use std::{
 12    ops::{Mul, Range},
 13    sync::Arc,
 14};
 15use theme::{ActiveTheme, SyntaxTheme};
 16use ui::{h_flex, v_flex, Checkbox, Selection};
 17use workspace::Workspace;
 18
 19pub struct RenderContext {
 20    workspace: Option<WeakView<Workspace>>,
 21    next_id: usize,
 22    text_style: TextStyle,
 23    border_color: Hsla,
 24    text_color: Hsla,
 25    text_muted_color: Hsla,
 26    code_block_background_color: Hsla,
 27    code_span_background_color: Hsla,
 28    syntax_theme: Arc<SyntaxTheme>,
 29    indent: usize,
 30}
 31
 32impl RenderContext {
 33    pub fn new(workspace: Option<WeakView<Workspace>>, cx: &WindowContext) -> RenderContext {
 34        let theme = cx.theme().clone();
 35
 36        RenderContext {
 37            workspace,
 38            next_id: 0,
 39            indent: 0,
 40            text_style: cx.text_style(),
 41            syntax_theme: theme.syntax().clone(),
 42            border_color: theme.colors().border,
 43            text_color: theme.colors().text,
 44            text_muted_color: theme.colors().text_muted,
 45            code_block_background_color: theme.colors().surface_background,
 46            code_span_background_color: theme.colors().editor_document_highlight_read_background,
 47        }
 48    }
 49
 50    fn next_id(&mut self, span: &Range<usize>) -> ElementId {
 51        let id = format!("markdown-{}-{}-{}", self.next_id, span.start, span.end);
 52        self.next_id += 1;
 53        ElementId::from(SharedString::from(id))
 54    }
 55
 56    /// This ensures that children inside of block quotes
 57    /// have padding between them.
 58    ///
 59    /// For example, for this markdown:
 60    ///
 61    /// ```markdown
 62    /// > This is a block quote.
 63    /// >
 64    /// > And this is the next paragraph.
 65    /// ```
 66    ///
 67    /// We give padding between "This is a block quote."
 68    /// and "And this is the next paragraph."
 69    fn with_common_p(&self, element: Div) -> Div {
 70        if self.indent > 0 {
 71            element.pb_3()
 72        } else {
 73            element
 74        }
 75    }
 76}
 77
 78pub fn render_parsed_markdown(
 79    parsed: &ParsedMarkdown,
 80    workspace: Option<WeakView<Workspace>>,
 81    cx: &WindowContext,
 82) -> Vec<AnyElement> {
 83    let mut cx = RenderContext::new(workspace, cx);
 84    let mut elements = Vec::new();
 85
 86    for child in &parsed.children {
 87        elements.push(render_markdown_block(child, &mut cx));
 88    }
 89
 90    return elements;
 91}
 92
 93pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
 94    use ParsedMarkdownElement::*;
 95    match block {
 96        Paragraph(text) => render_markdown_paragraph(text, cx),
 97        Heading(heading) => render_markdown_heading(heading, cx),
 98        List(list) => render_markdown_list(list, cx),
 99        Table(table) => render_markdown_table(table, cx),
100        BlockQuote(block_quote) => render_markdown_block_quote(block_quote, cx),
101        CodeBlock(code_block) => render_markdown_code_block(code_block, cx),
102        HorizontalRule(_) => render_markdown_rule(cx),
103    }
104}
105
106fn render_markdown_heading(parsed: &ParsedMarkdownHeading, cx: &mut RenderContext) -> AnyElement {
107    let size = match parsed.level {
108        HeadingLevel::H1 => rems(2.),
109        HeadingLevel::H2 => rems(1.5),
110        HeadingLevel::H3 => rems(1.25),
111        HeadingLevel::H4 => rems(1.),
112        HeadingLevel::H5 => rems(0.875),
113        HeadingLevel::H6 => rems(0.85),
114    };
115
116    let color = match parsed.level {
117        HeadingLevel::H6 => cx.text_muted_color,
118        _ => cx.text_color,
119    };
120
121    let line_height = DefiniteLength::from(size.mul(1.25));
122
123    div()
124        .line_height(line_height)
125        .text_size(size)
126        .text_color(color)
127        .pt(rems(0.15))
128        .pb_1()
129        .child(render_markdown_text(&parsed.contents, cx))
130        .whitespace_normal()
131        .into_any()
132}
133
134fn render_markdown_list(parsed: &ParsedMarkdownList, cx: &mut RenderContext) -> AnyElement {
135    use ParsedMarkdownListItemType::*;
136
137    let mut items = vec![];
138    for item in &parsed.children {
139        let padding = rems((item.depth - 1) as f32 * 0.25);
140
141        let bullet = match item.item_type {
142            Ordered(order) => format!("{}.", order).into_any_element(),
143            Unordered => "".into_any_element(),
144            Task(checked) => div()
145                .mt(px(3.))
146                .child(Checkbox::new(
147                    "checkbox",
148                    if checked {
149                        Selection::Selected
150                    } else {
151                        Selection::Unselected
152                    },
153                ))
154                .into_any_element(),
155        };
156        let bullet = div().mr_2().child(bullet);
157
158        let contents: Vec<AnyElement> = item
159            .contents
160            .iter()
161            .map(|c| render_markdown_block(c.as_ref(), cx))
162            .collect();
163
164        let item = h_flex()
165            .pl(DefiniteLength::Absolute(AbsoluteLength::Rems(padding)))
166            .items_start()
167            .children(vec![bullet, div().children(contents).pr_4().w_full()]);
168
169        items.push(item);
170    }
171
172    cx.with_common_p(div()).children(items).into_any()
173}
174
175fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
176    let header = render_markdown_table_row(&parsed.header, &parsed.column_alignments, true, cx);
177
178    let body: Vec<AnyElement> = parsed
179        .body
180        .iter()
181        .map(|row| render_markdown_table_row(row, &parsed.column_alignments, false, cx))
182        .collect();
183
184    cx.with_common_p(v_flex())
185        .w_full()
186        .child(header)
187        .children(body)
188        .into_any()
189}
190
191fn render_markdown_table_row(
192    parsed: &ParsedMarkdownTableRow,
193    alignments: &Vec<ParsedMarkdownTableAlignment>,
194    is_header: bool,
195    cx: &mut RenderContext,
196) -> AnyElement {
197    let mut items = vec![];
198
199    for cell in &parsed.children {
200        let alignment = alignments
201            .get(items.len())
202            .copied()
203            .unwrap_or(ParsedMarkdownTableAlignment::None);
204
205        let contents = render_markdown_text(cell, cx);
206
207        let container = match alignment {
208            ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
209            ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
210            ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
211        };
212
213        let mut cell = container
214            .w_full()
215            .child(contents)
216            .px_2()
217            .py_1()
218            .border_color(cx.border_color);
219
220        if is_header {
221            cell = cell.border_2()
222        } else {
223            cell = cell.border_1()
224        }
225
226        items.push(cell);
227    }
228
229    h_flex().children(items).into_any_element()
230}
231
232fn render_markdown_block_quote(
233    parsed: &ParsedMarkdownBlockQuote,
234    cx: &mut RenderContext,
235) -> AnyElement {
236    cx.indent += 1;
237
238    let children: Vec<AnyElement> = parsed
239        .children
240        .iter()
241        .map(|child| render_markdown_block(child, cx))
242        .collect();
243
244    cx.indent -= 1;
245
246    cx.with_common_p(div())
247        .child(
248            div()
249                .border_l_4()
250                .border_color(cx.border_color)
251                .pl_3()
252                .children(children),
253        )
254        .into_any()
255}
256
257fn render_markdown_code_block(
258    parsed: &ParsedMarkdownCodeBlock,
259    cx: &mut RenderContext,
260) -> AnyElement {
261    let body = if let Some(highlights) = parsed.highlights.as_ref() {
262        StyledText::new(parsed.contents.clone()).with_highlights(
263            &cx.text_style,
264            highlights.iter().filter_map(|(range, highlight_id)| {
265                highlight_id
266                    .style(cx.syntax_theme.as_ref())
267                    .map(|style| (range.clone(), style))
268            }),
269        )
270    } else {
271        StyledText::new(parsed.contents.clone())
272    };
273
274    cx.with_common_p(div())
275        .px_3()
276        .py_3()
277        .bg(cx.code_block_background_color)
278        .rounded_md()
279        .child(body)
280        .into_any()
281}
282
283fn render_markdown_paragraph(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
284    cx.with_common_p(div())
285        .child(render_markdown_text(parsed, cx))
286        .into_any_element()
287}
288
289fn render_markdown_text(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
290    let element_id = cx.next_id(&parsed.source_range);
291
292    let highlights = gpui::combine_highlights(
293        parsed.highlights.iter().filter_map(|(range, highlight)| {
294            let highlight = highlight.to_highlight_style(&cx.syntax_theme)?;
295            Some((range.clone(), highlight))
296        }),
297        parsed
298            .regions
299            .iter()
300            .zip(&parsed.region_ranges)
301            .filter_map(|(region, range)| {
302                if region.code {
303                    Some((
304                        range.clone(),
305                        HighlightStyle {
306                            background_color: Some(cx.code_span_background_color),
307                            ..Default::default()
308                        },
309                    ))
310                } else {
311                    None
312                }
313            }),
314    );
315
316    let mut links = Vec::new();
317    let mut link_ranges = Vec::new();
318    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
319        if let Some(link) = region.link.clone() {
320            links.push(link);
321            link_ranges.push(range.clone());
322        }
323    }
324
325    let workspace = cx.workspace.clone();
326
327    InteractiveText::new(
328        element_id,
329        StyledText::new(parsed.contents.clone()).with_highlights(&cx.text_style, highlights),
330    )
331    .on_click(
332        link_ranges,
333        move |clicked_range_ix, window_cx| match &links[clicked_range_ix] {
334            Link::Web { url } => window_cx.open_url(url),
335            Link::Path { path } => {
336                if let Some(workspace) = &workspace {
337                    _ = workspace.update(window_cx, |workspace, cx| {
338                        workspace.open_abs_path(path.clone(), false, cx).detach();
339                    });
340                }
341            }
342        },
343    )
344    .into_any_element()
345}
346
347fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
348    let rule = div().w_full().h(px(2.)).bg(cx.border_color);
349    div().pt_3().pb_3().child(rule).into_any()
350}