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, Modifiers, ParentElement,
10 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, 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 header = render_markdown_table_row(&parsed.header, &parsed.column_alignments, true, cx);
235
236 let body: Vec<AnyElement> = parsed
237 .body
238 .iter()
239 .map(|row| render_markdown_table_row(row, &parsed.column_alignments, false, cx))
240 .collect();
241
242 cx.with_common_p(v_flex())
243 .w_full()
244 .child(header)
245 .children(body)
246 .into_any()
247}
248
249fn render_markdown_table_row(
250 parsed: &ParsedMarkdownTableRow,
251 alignments: &Vec<ParsedMarkdownTableAlignment>,
252 is_header: bool,
253 cx: &mut RenderContext,
254) -> AnyElement {
255 let mut items = vec![];
256
257 for cell in &parsed.children {
258 let alignment = alignments
259 .get(items.len())
260 .copied()
261 .unwrap_or(ParsedMarkdownTableAlignment::None);
262
263 let contents = render_markdown_text(cell, cx);
264
265 let container = match alignment {
266 ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
267 ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
268 ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
269 };
270
271 let mut cell = container
272 .w_full()
273 .child(contents)
274 .px_2()
275 .py_1()
276 .border_color(cx.border_color);
277
278 if is_header {
279 cell = cell.border_2()
280 } else {
281 cell = cell.border_1()
282 }
283
284 items.push(cell);
285 }
286
287 h_flex().children(items).into_any_element()
288}
289
290fn render_markdown_block_quote(
291 parsed: &ParsedMarkdownBlockQuote,
292 cx: &mut RenderContext,
293) -> AnyElement {
294 cx.indent += 1;
295
296 let children: Vec<AnyElement> = parsed
297 .children
298 .iter()
299 .map(|child| render_markdown_block(child, cx))
300 .collect();
301
302 cx.indent -= 1;
303
304 cx.with_common_p(div())
305 .child(
306 div()
307 .border_l_4()
308 .border_color(cx.border_color)
309 .pl_3()
310 .children(children),
311 )
312 .into_any()
313}
314
315fn render_markdown_code_block(
316 parsed: &ParsedMarkdownCodeBlock,
317 cx: &mut RenderContext,
318) -> AnyElement {
319 let body = if let Some(highlights) = parsed.highlights.as_ref() {
320 StyledText::new(parsed.contents.clone()).with_highlights(
321 &cx.buffer_text_style,
322 highlights.iter().filter_map(|(range, highlight_id)| {
323 highlight_id
324 .style(cx.syntax_theme.as_ref())
325 .map(|style| (range.clone(), style))
326 }),
327 )
328 } else {
329 StyledText::new(parsed.contents.clone())
330 };
331
332 cx.with_common_p(div())
333 .font_family(cx.buffer_font_family.clone())
334 .px_3()
335 .py_3()
336 .bg(cx.code_block_background_color)
337 .rounded_md()
338 .child(body)
339 .into_any()
340}
341
342fn render_markdown_paragraph(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
343 cx.with_common_p(div())
344 .child(render_markdown_text(parsed, cx))
345 .into_any_element()
346}
347
348fn render_markdown_text(parsed: &ParsedMarkdownText, cx: &mut RenderContext) -> AnyElement {
349 let element_id = cx.next_id(&parsed.source_range);
350
351 let highlights = gpui::combine_highlights(
352 parsed.highlights.iter().filter_map(|(range, highlight)| {
353 let highlight = highlight.to_highlight_style(&cx.syntax_theme)?;
354 Some((range.clone(), highlight))
355 }),
356 parsed
357 .regions
358 .iter()
359 .zip(&parsed.region_ranges)
360 .filter_map(|(region, range)| {
361 if region.code {
362 Some((
363 range.clone(),
364 HighlightStyle {
365 background_color: Some(cx.code_span_background_color),
366 ..Default::default()
367 },
368 ))
369 } else {
370 None
371 }
372 }),
373 );
374
375 let mut links = Vec::new();
376 let mut link_ranges = Vec::new();
377 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
378 if let Some(link) = region.link.clone() {
379 links.push(link);
380 link_ranges.push(range.clone());
381 }
382 }
383
384 let workspace = cx.workspace.clone();
385
386 InteractiveText::new(
387 element_id,
388 StyledText::new(parsed.contents.clone()).with_highlights(&cx.text_style, highlights),
389 )
390 .tooltip({
391 let links = links.clone();
392 let link_ranges = link_ranges.clone();
393 move |idx, cx| {
394 for (ix, range) in link_ranges.iter().enumerate() {
395 if range.contains(&idx) {
396 return Some(LinkPreview::new(&links[ix].to_string(), cx));
397 }
398 }
399 None
400 }
401 })
402 .on_click(
403 link_ranges,
404 move |clicked_range_ix, window_cx| match &links[clicked_range_ix] {
405 Link::Web { url } => window_cx.open_url(url),
406 Link::Path {
407 path,
408 display_path: _,
409 } => {
410 if let Some(workspace) = &workspace {
411 _ = workspace.update(window_cx, |workspace, cx| {
412 workspace.open_abs_path(path.clone(), false, cx).detach();
413 });
414 }
415 }
416 },
417 )
418 .into_any_element()
419}
420
421fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
422 let rule = div().w_full().h(px(2.)).bg(cx.border_color);
423 div().pt_3().pb_3().child(rule).into_any()
424}