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