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, Label};
 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),
143            Unordered => "".to_string(),
144            Task(checked) => if checked { "" } else { "" }.to_string(),
145        };
146        let bullet = div().mr_2().child(Label::new(bullet));
147
148        let contents: Vec<AnyElement> = item
149            .contents
150            .iter()
151            .map(|c| render_markdown_block(c.as_ref(), cx))
152            .collect();
153
154        let item = h_flex()
155            .pl(DefiniteLength::Absolute(AbsoluteLength::Rems(padding)))
156            .items_start()
157            .children(vec![bullet, div().children(contents).pr_4().w_full()]);
158
159        items.push(item);
160    }
161
162    cx.with_common_p(div()).children(items).into_any()
163}
164
165fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
166    let header = render_markdown_table_row(&parsed.header, &parsed.column_alignments, true, cx);
167
168    let body: Vec<AnyElement> = parsed
169        .body
170        .iter()
171        .map(|row| render_markdown_table_row(row, &parsed.column_alignments, false, cx))
172        .collect();
173
174    cx.with_common_p(v_flex())
175        .w_full()
176        .child(header)
177        .children(body)
178        .into_any()
179}
180
181fn render_markdown_table_row(
182    parsed: &ParsedMarkdownTableRow,
183    alignments: &Vec<ParsedMarkdownTableAlignment>,
184    is_header: bool,
185    cx: &mut RenderContext,
186) -> AnyElement {
187    let mut items = vec![];
188
189    for cell in &parsed.children {
190        let alignment = alignments
191            .get(items.len())
192            .copied()
193            .unwrap_or(ParsedMarkdownTableAlignment::None);
194
195        let contents = render_markdown_text(cell, cx);
196
197        let container = match alignment {
198            ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
199            ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
200            ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
201        };
202
203        let mut cell = container
204            .w_full()
205            .child(contents)
206            .px_2()
207            .py_1()
208            .border_color(cx.border_color);
209
210        if is_header {
211            cell = cell.border_2()
212        } else {
213            cell = cell.border_1()
214        }
215
216        items.push(cell);
217    }
218
219    h_flex().children(items).into_any_element()
220}
221
222fn render_markdown_block_quote(
223    parsed: &ParsedMarkdownBlockQuote,
224    cx: &mut RenderContext,
225) -> AnyElement {
226    cx.indent += 1;
227
228    let children: Vec<AnyElement> = parsed
229        .children
230        .iter()
231        .map(|child| render_markdown_block(child, cx))
232        .collect();
233
234    cx.indent -= 1;
235
236    cx.with_common_p(div())
237        .child(
238            div()
239                .border_l_4()
240                .border_color(cx.border_color)
241                .pl_3()
242                .children(children),
243        )
244        .into_any()
245}
246
247fn render_markdown_code_block(
248    parsed: &ParsedMarkdownCodeBlock,
249    cx: &mut RenderContext,
250) -> AnyElement {
251    let body = if let Some(highlights) = parsed.highlights.as_ref() {
252        StyledText::new(parsed.contents.clone()).with_highlights(
253            &cx.text_style,
254            highlights.iter().filter_map(|(range, highlight_id)| {
255                highlight_id
256                    .style(cx.syntax_theme.as_ref())
257                    .map(|style| (range.clone(), style))
258            }),
259        )
260    } else {
261        StyledText::new(parsed.contents.clone())
262    };
263
264    cx.with_common_p(div())
265        .px_3()
266        .py_3()
267        .bg(cx.code_block_background_color)
268        .rounded_md()
269        .child(body)
270        .into_any()
271}
272
273fn render_markdown_paragraph(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
274    cx.with_common_p(div())
275        .child(render_markdown_text(parsed, cx))
276        .into_any_element()
277}
278
279fn render_markdown_text(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
280    let element_id = cx.next_id(&parsed.source_range);
281
282    let highlights = gpui::combine_highlights(
283        parsed.highlights.iter().filter_map(|(range, highlight)| {
284            let highlight = highlight.to_highlight_style(&cx.syntax_theme)?;
285            Some((range.clone(), highlight))
286        }),
287        parsed
288            .regions
289            .iter()
290            .zip(&parsed.region_ranges)
291            .filter_map(|(region, range)| {
292                if region.code {
293                    Some((
294                        range.clone(),
295                        HighlightStyle {
296                            background_color: Some(cx.code_span_background_color),
297                            ..Default::default()
298                        },
299                    ))
300                } else {
301                    None
302                }
303            }),
304    );
305
306    let mut links = Vec::new();
307    let mut link_ranges = Vec::new();
308    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
309        if let Some(link) = region.link.clone() {
310            links.push(link);
311            link_ranges.push(range.clone());
312        }
313    }
314
315    let workspace = cx.workspace.clone();
316
317    InteractiveText::new(
318        element_id,
319        StyledText::new(parsed.contents.clone()).with_highlights(&cx.text_style, highlights),
320    )
321    .on_click(
322        link_ranges,
323        move |clicked_range_ix, window_cx| match &links[clicked_range_ix] {
324            Link::Web { url } => window_cx.open_url(url),
325            Link::Path { path } => {
326                if let Some(workspace) = &workspace {
327                    _ = workspace.update(window_cx, |workspace, cx| {
328                        workspace.open_abs_path(path.clone(), false, cx).detach();
329                    });
330                }
331            }
332        },
333    )
334    .into_any_element()
335}
336
337fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
338    let rule = div().w_full().h(px(2.)).bg(cx.border_color);
339    div().pt_3().pb_3().child(rule).into_any()
340}