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