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
237 let bullet = match &parsed.item_type {
238 Ordered(order) => format!("{}.", order).into_any_element(),
239 Unordered => "•".into_any_element(),
240 Task(checked, range) => div()
241 .id(cx.next_id(range))
242 .mt(cx.scaled_rems(3.0 / 16.0))
243 .child(
244 MarkdownCheckbox::new(
245 "checkbox",
246 if *checked {
247 ToggleState::Selected
248 } else {
249 ToggleState::Unselected
250 },
251 cx.clone(),
252 )
253 .when_some(
254 cx.checkbox_clicked_callback.clone(),
255 |this, callback| {
256 this.on_click({
257 let range = range.clone();
258 move |selection, window, cx| {
259 let checked = match selection {
260 ToggleState::Selected => true,
261 ToggleState::Unselected => false,
262 _ => return,
263 };
264
265 if window.modifiers().secondary() {
266 callback(
267 &CheckboxClickedEvent {
268 checked,
269 source_range: range.clone(),
270 },
271 window,
272 cx,
273 );
274 }
275 }
276 })
277 },
278 ),
279 )
280 .hover(|s| s.cursor_pointer())
281 .tooltip(|_, cx| {
282 InteractiveMarkdownElementTooltip::new(None, "toggle checkbox", cx).into()
283 })
284 .into_any_element(),
285 };
286 let bullet = div().mr(cx.scaled_rems(0.5)).child(bullet);
287
288 let contents: Vec<AnyElement> = parsed
289 .content
290 .iter()
291 .map(|c| render_markdown_block(c, cx))
292 .collect();
293
294 let item = h_flex()
295 .when(!parsed.nested, |this| {
296 this.pl(cx.scaled_rems(parsed.depth.saturating_sub(1) as f32))
297 })
298 .when(parsed.nested && parsed.depth > 1, |this| this.ml_neg_1p5())
299 .items_start()
300 .children(vec![
301 bullet,
302 v_flex()
303 .children(contents)
304 .when(!parsed.nested, |this| this.gap(cx.scaled_rems(1.0)))
305 .pr(cx.scaled_rems(1.0))
306 .w_full(),
307 ]);
308
309 cx.with_common_p(item).into_any()
310}
311
312/// # MarkdownCheckbox ///
313/// HACK: Copied from `ui/src/components/toggle.rs` to deal with scaling issues in markdown preview
314/// changes should be integrated into `Checkbox` in `toggle.rs` while making sure checkboxes elsewhere in the
315/// app are not visually affected
316#[derive(gpui::IntoElement)]
317struct MarkdownCheckbox {
318 id: ElementId,
319 toggle_state: ToggleState,
320 disabled: bool,
321 placeholder: bool,
322 on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
323 filled: bool,
324 style: ui::ToggleStyle,
325 tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
326 label: Option<SharedString>,
327 render_cx: RenderContext,
328}
329
330impl MarkdownCheckbox {
331 /// Creates a new [`Checkbox`].
332 fn new(id: impl Into<ElementId>, checked: ToggleState, render_cx: RenderContext) -> Self {
333 Self {
334 id: id.into(),
335 toggle_state: checked,
336 disabled: false,
337 on_click: None,
338 filled: false,
339 style: ui::ToggleStyle::default(),
340 tooltip: None,
341 label: None,
342 placeholder: false,
343 render_cx,
344 }
345 }
346
347 /// Binds a handler to the [`Checkbox`] that will be called when clicked.
348 fn on_click(mut self, handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static) -> Self {
349 self.on_click = Some(Box::new(handler));
350 self
351 }
352
353 fn bg_color(&self, cx: &App) -> Hsla {
354 let style = self.style.clone();
355 match (style, self.filled) {
356 (ui::ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
357 (ui::ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
358 (ui::ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
359 (ui::ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
360 (ui::ToggleStyle::Custom(_), false) => gpui::transparent_black(),
361 (ui::ToggleStyle::Custom(color), true) => color.opacity(0.2),
362 }
363 }
364
365 fn border_color(&self, cx: &App) -> Hsla {
366 if self.disabled {
367 return cx.theme().colors().border_variant;
368 }
369
370 match self.style.clone() {
371 ui::ToggleStyle::Ghost => cx.theme().colors().border,
372 ui::ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
373 ui::ToggleStyle::Custom(color) => color.opacity(0.3),
374 }
375 }
376}
377
378impl gpui::RenderOnce for MarkdownCheckbox {
379 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
380 let group_id = format!("checkbox_group_{:?}", self.id);
381 let color = if self.disabled {
382 Color::Disabled
383 } else {
384 Color::Selected
385 };
386 let icon_size_small = IconSize::Custom(self.render_cx.scaled_rems(14. / 16.)); // was IconSize::Small
387 let icon = match self.toggle_state {
388 ToggleState::Selected => {
389 if self.placeholder {
390 None
391 } else {
392 Some(
393 ui::Icon::new(IconName::Check)
394 .size(icon_size_small)
395 .color(color),
396 )
397 }
398 }
399 ToggleState::Indeterminate => Some(
400 ui::Icon::new(IconName::Dash)
401 .size(icon_size_small)
402 .color(color),
403 ),
404 ToggleState::Unselected => None,
405 };
406
407 let bg_color = self.bg_color(cx);
408 let border_color = self.border_color(cx);
409 let hover_border_color = border_color.alpha(0.7);
410
411 let size = self.render_cx.scaled_rems(1.25); // was Self::container_size(); (20px)
412
413 let checkbox = h_flex()
414 .id(self.id.clone())
415 .justify_center()
416 .items_center()
417 .size(size)
418 .group(group_id.clone())
419 .child(
420 div()
421 .flex()
422 .flex_none()
423 .justify_center()
424 .items_center()
425 .m(self.render_cx.scaled_rems(0.25)) // was .m_1
426 .size(self.render_cx.scaled_rems(1.0)) // was .size_4
427 .rounded(self.render_cx.scaled_rems(0.125)) // was .rounded_xs
428 .border_1()
429 .bg(bg_color)
430 .border_color(border_color)
431 .when(self.disabled, |this| this.cursor_not_allowed())
432 .when(self.disabled, |this| {
433 this.bg(cx.theme().colors().element_disabled.opacity(0.6))
434 })
435 .when(!self.disabled, |this| {
436 this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
437 })
438 .when(self.placeholder, |this| {
439 this.child(
440 div()
441 .flex_none()
442 .rounded_full()
443 .bg(color.color(cx).alpha(0.5))
444 .size(self.render_cx.scaled_rems(0.25)), // was .size_1
445 )
446 })
447 .children(icon),
448 );
449
450 h_flex()
451 .id(self.id)
452 .gap(ui::DynamicSpacing::Base06.rems(cx))
453 .child(checkbox)
454 .when_some(
455 self.on_click.filter(|_| !self.disabled),
456 |this, on_click| {
457 this.on_click(move |_, window, cx| {
458 on_click(&self.toggle_state.inverse(), window, cx)
459 })
460 },
461 )
462 // TODO: Allow label size to be different from default.
463 // TODO: Allow label color to be different from muted.
464 .when_some(self.label, |this, label| {
465 this.child(Label::new(label).color(Color::Muted))
466 })
467 .when_some(self.tooltip, |this, tooltip| {
468 this.tooltip(move |window, cx| tooltip(window, cx))
469 })
470 }
471}
472
473fn calculate_table_columns_count(rows: &Vec<ParsedMarkdownTableRow>) -> usize {
474 let mut actual_column_count = 0;
475 for row in rows {
476 actual_column_count = actual_column_count.max(
477 row.columns
478 .iter()
479 .map(|column| column.col_span)
480 .sum::<usize>(),
481 );
482 }
483 actual_column_count
484}
485
486fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
487 let actual_header_column_count = calculate_table_columns_count(&parsed.header);
488 let actual_body_column_count = calculate_table_columns_count(&parsed.body);
489 let max_column_count = std::cmp::max(actual_header_column_count, actual_body_column_count);
490
491 let total_rows = parsed.header.len() + parsed.body.len();
492
493 // Track which grid cells are occupied by spanning cells
494 let mut grid_occupied = vec![vec![false; max_column_count]; total_rows];
495
496 let mut cells = Vec::with_capacity(total_rows * max_column_count);
497
498 for (row_idx, row) in parsed.header.iter().chain(parsed.body.iter()).enumerate() {
499 let mut col_idx = 0;
500
501 for cell in row.columns.iter() {
502 // Skip columns occupied by row-spanning cells from previous rows
503 while col_idx < max_column_count && grid_occupied[row_idx][col_idx] {
504 col_idx += 1;
505 }
506
507 if col_idx >= max_column_count {
508 break;
509 }
510
511 let container = match cell.alignment {
512 ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
513 ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
514 ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
515 };
516
517 let cell_element = container
518 .col_span(cell.col_span.min(max_column_count - col_idx) as u16)
519 .row_span(cell.row_span.min(total_rows - row_idx) as u16)
520 .children(render_markdown_text(&cell.children, cx))
521 .px_2()
522 .py_1()
523 .border_1()
524 .size_full()
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 .size_full()
556 .border_color(cx.border_color)
557 .when(row_idx % 2 == 1, |this| this.bg(cx.panel_background_color));
558
559 cells.push(empty_cell);
560 col_idx += 1;
561 }
562 }
563
564 cx.with_common_p(div())
565 .grid()
566 .size_full()
567 .grid_cols(max_column_count as u16)
568 .border_1()
569 .border_color(cx.border_color)
570 .children(cells)
571 .into_any()
572}
573
574fn render_markdown_block_quote(
575 parsed: &ParsedMarkdownBlockQuote,
576 cx: &mut RenderContext,
577) -> AnyElement {
578 cx.indent += 1;
579
580 let children: Vec<AnyElement> = parsed
581 .children
582 .iter()
583 .enumerate()
584 .map(|(ix, child)| {
585 cx.with_last_child(ix + 1 == parsed.children.len(), |cx| {
586 render_markdown_block(child, cx)
587 })
588 })
589 .collect();
590
591 cx.indent -= 1;
592
593 cx.with_common_p(div())
594 .child(
595 div()
596 .border_l_4()
597 .border_color(cx.border_color)
598 .pl_3()
599 .children(children),
600 )
601 .into_any()
602}
603
604fn render_markdown_code_block(
605 parsed: &ParsedMarkdownCodeBlock,
606 cx: &mut RenderContext,
607) -> AnyElement {
608 let body = if let Some(highlights) = parsed.highlights.as_ref() {
609 StyledText::new(parsed.contents.clone()).with_default_highlights(
610 &cx.buffer_text_style,
611 highlights.iter().filter_map(|(range, highlight_id)| {
612 highlight_id
613 .style(cx.syntax_theme.as_ref())
614 .map(|style| (range.clone(), style))
615 }),
616 )
617 } else {
618 StyledText::new(parsed.contents.clone())
619 };
620
621 let copy_block_button = IconButton::new("copy-code", IconName::Copy)
622 .icon_size(IconSize::Small)
623 .on_click({
624 let contents = parsed.contents.clone();
625 move |_, _window, cx| {
626 cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
627 }
628 })
629 .tooltip(Tooltip::text("Copy code block"))
630 .visible_on_hover("markdown-block");
631
632 cx.with_common_p(div())
633 .font_family(cx.buffer_font_family.clone())
634 .px_3()
635 .py_3()
636 .bg(cx.code_block_background_color)
637 .rounded_sm()
638 .child(body)
639 .child(
640 div()
641 .h_flex()
642 .absolute()
643 .right_1()
644 .top_1()
645 .child(copy_block_button),
646 )
647 .into_any()
648}
649
650fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
651 cx.with_common_p(div())
652 .children(render_markdown_text(parsed, cx))
653 .flex()
654 .flex_col()
655 .into_any_element()
656}
657
658fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
659 let mut any_element = Vec::with_capacity(parsed_new.len());
660 // these values are cloned in-order satisfy borrow checker
661 let syntax_theme = cx.syntax_theme.clone();
662 let workspace_clone = cx.workspace.clone();
663 let code_span_bg_color = cx.code_span_background_color;
664 let text_style = cx.text_style.clone();
665 let link_color = cx.link_color;
666
667 for parsed_region in parsed_new {
668 match parsed_region {
669 MarkdownParagraphChunk::Text(parsed) => {
670 let element_id = cx.next_id(&parsed.source_range);
671
672 let highlights = gpui::combine_highlights(
673 parsed.highlights.iter().filter_map(|(range, highlight)| {
674 highlight
675 .to_highlight_style(&syntax_theme)
676 .map(|style| (range.clone(), style))
677 }),
678 parsed.regions.iter().zip(&parsed.region_ranges).filter_map(
679 |(region, range)| {
680 if region.code {
681 Some((
682 range.clone(),
683 HighlightStyle {
684 background_color: Some(code_span_bg_color),
685 ..Default::default()
686 },
687 ))
688 } else if region.link.is_some() {
689 Some((
690 range.clone(),
691 HighlightStyle {
692 color: Some(link_color),
693 ..Default::default()
694 },
695 ))
696 } else {
697 None
698 }
699 },
700 ),
701 );
702 let mut links = Vec::new();
703 let mut link_ranges = Vec::new();
704 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
705 if let Some(link) = region.link.clone() {
706 links.push(link);
707 link_ranges.push(range.clone());
708 }
709 }
710 let workspace = workspace_clone.clone();
711 let element = div()
712 .child(
713 InteractiveText::new(
714 element_id,
715 StyledText::new(parsed.contents.clone())
716 .with_default_highlights(&text_style, highlights),
717 )
718 .tooltip({
719 let links = links.clone();
720 let link_ranges = link_ranges.clone();
721 move |idx, _, cx| {
722 for (ix, range) in link_ranges.iter().enumerate() {
723 if range.contains(&idx) {
724 return Some(LinkPreview::new(&links[ix].to_string(), cx));
725 }
726 }
727 None
728 }
729 })
730 .on_click(
731 link_ranges,
732 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
733 Link::Web { url } => cx.open_url(url),
734 Link::Path { path, .. } => {
735 if let Some(workspace) = &workspace {
736 _ = workspace.update(cx, |workspace, cx| {
737 workspace
738 .open_abs_path(
739 normalize_path(path.clone().as_path()),
740 OpenOptions {
741 visible: Some(OpenVisible::None),
742 ..Default::default()
743 },
744 window,
745 cx,
746 )
747 .detach();
748 });
749 }
750 }
751 },
752 ),
753 )
754 .into_any();
755 any_element.push(element);
756 }
757
758 MarkdownParagraphChunk::Image(image) => {
759 any_element.push(render_markdown_image(image, cx));
760 }
761 }
762 }
763
764 any_element
765}
766
767fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
768 let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
769 div().py(cx.scaled_rems(0.5)).child(rule).into_any()
770}
771
772fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
773 let image_resource = match image.link.clone() {
774 Link::Web { url } => Resource::Uri(url.into()),
775 Link::Path { path, .. } => Resource::Path(Arc::from(path)),
776 };
777
778 let element_id = cx.next_id(&image.source_range);
779 let workspace = cx.workspace.clone();
780
781 div()
782 .id(element_id)
783 .cursor_pointer()
784 .child(
785 img(ImageSource::Resource(image_resource))
786 .max_w_full()
787 .with_fallback({
788 let alt_text = image.alt_text.clone();
789 move || div().children(alt_text.clone()).into_any_element()
790 })
791 .when_some(image.height, |this, height| this.h(height))
792 .when_some(image.width, |this, width| this.w(width)),
793 )
794 .tooltip({
795 let link = image.link.clone();
796 let alt_text = image.alt_text.clone();
797 move |_, cx| {
798 InteractiveMarkdownElementTooltip::new(
799 Some(alt_text.clone().unwrap_or(link.to_string().into())),
800 "open image",
801 cx,
802 )
803 .into()
804 }
805 })
806 .on_click({
807 let link = image.link.clone();
808 move |_, window, cx| {
809 if window.modifiers().secondary() {
810 match &link {
811 Link::Web { url } => cx.open_url(url),
812 Link::Path { path, .. } => {
813 if let Some(workspace) = &workspace {
814 _ = workspace.update(cx, |workspace, cx| {
815 workspace
816 .open_abs_path(
817 path.clone(),
818 OpenOptions {
819 visible: Some(OpenVisible::None),
820 ..Default::default()
821 },
822 window,
823 cx,
824 )
825 .detach();
826 });
827 }
828 }
829 }
830 }
831 }
832 })
833 .into_any()
834}
835
836struct InteractiveMarkdownElementTooltip {
837 tooltip_text: Option<SharedString>,
838 action_text: SharedString,
839}
840
841impl InteractiveMarkdownElementTooltip {
842 pub fn new(
843 tooltip_text: Option<SharedString>,
844 action_text: impl Into<SharedString>,
845 cx: &mut App,
846 ) -> Entity<Self> {
847 let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
848
849 cx.new(|_cx| Self {
850 tooltip_text,
851 action_text: action_text.into(),
852 })
853 }
854}
855
856impl Render for InteractiveMarkdownElementTooltip {
857 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
858 tooltip_container(cx, |el, _| {
859 let secondary_modifier = Keystroke {
860 modifiers: Modifiers::secondary_key(),
861 ..Default::default()
862 };
863
864 el.child(
865 v_flex()
866 .gap_1()
867 .when_some(self.tooltip_text.clone(), |this, text| {
868 this.child(Label::new(text).size(LabelSize::Small))
869 })
870 .child(
871 Label::new(format!(
872 "{}-click to {}",
873 secondary_modifier, self.action_text
874 ))
875 .size(LabelSize::Small)
876 .color(Color::Muted),
877 ),
878 )
879 })
880 }
881}
882
883#[cfg(test)]
884mod tests {
885 use super::*;
886 use crate::markdown_elements::ParsedMarkdownTableColumn;
887 use crate::markdown_elements::ParsedMarkdownText;
888
889 fn text(text: &str) -> MarkdownParagraphChunk {
890 MarkdownParagraphChunk::Text(ParsedMarkdownText {
891 source_range: 0..text.len(),
892 contents: SharedString::new(text),
893 highlights: Default::default(),
894 region_ranges: Default::default(),
895 regions: Default::default(),
896 })
897 }
898
899 fn column(
900 col_span: usize,
901 row_span: usize,
902 children: Vec<MarkdownParagraphChunk>,
903 ) -> ParsedMarkdownTableColumn {
904 ParsedMarkdownTableColumn {
905 col_span,
906 row_span,
907 is_header: false,
908 children,
909 alignment: ParsedMarkdownTableAlignment::None,
910 }
911 }
912
913 fn column_with_row_span(
914 col_span: usize,
915 row_span: usize,
916 children: Vec<MarkdownParagraphChunk>,
917 ) -> ParsedMarkdownTableColumn {
918 ParsedMarkdownTableColumn {
919 col_span,
920 row_span,
921 is_header: false,
922 children,
923 alignment: ParsedMarkdownTableAlignment::None,
924 }
925 }
926
927 #[test]
928 fn test_calculate_table_columns_count() {
929 assert_eq!(0, calculate_table_columns_count(&vec![]));
930
931 assert_eq!(
932 1,
933 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
934 column(1, 1, vec![text("column1")])
935 ])])
936 );
937
938 assert_eq!(
939 2,
940 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
941 column(1, 1, vec![text("column1")]),
942 column(1, 1, vec![text("column2")]),
943 ])])
944 );
945
946 assert_eq!(
947 2,
948 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
949 column(2, 1, vec![text("column1")])
950 ])])
951 );
952
953 assert_eq!(
954 3,
955 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
956 column(1, 1, vec![text("column1")]),
957 column(2, 1, vec![text("column2")]),
958 ])])
959 );
960
961 assert_eq!(
962 2,
963 calculate_table_columns_count(&vec![
964 ParsedMarkdownTableRow::with_columns(vec![
965 column(1, 1, vec![text("column1")]),
966 column(1, 1, vec![text("column2")]),
967 ]),
968 ParsedMarkdownTableRow::with_columns(vec![column(1, 1, vec![text("column1")]),])
969 ])
970 );
971
972 assert_eq!(
973 3,
974 calculate_table_columns_count(&vec![
975 ParsedMarkdownTableRow::with_columns(vec![
976 column(1, 1, vec![text("column1")]),
977 column(1, 1, vec![text("column2")]),
978 ]),
979 ParsedMarkdownTableRow::with_columns(vec![column(3, 3, vec![text("column1")]),])
980 ])
981 );
982 }
983
984 #[test]
985 fn test_row_span_support() {
986 assert_eq!(
987 3,
988 calculate_table_columns_count(&vec![
989 ParsedMarkdownTableRow::with_columns(vec![
990 column_with_row_span(1, 2, vec![text("spans 2 rows")]),
991 column(1, 1, vec![text("column2")]),
992 column(1, 1, vec![text("column3")]),
993 ]),
994 ParsedMarkdownTableRow::with_columns(vec![
995 // First column is covered by row span from above
996 column(1, 1, vec![text("column2 row2")]),
997 column(1, 1, vec![text("column3 row2")]),
998 ])
999 ])
1000 );
1001
1002 assert_eq!(
1003 4,
1004 calculate_table_columns_count(&vec![
1005 ParsedMarkdownTableRow::with_columns(vec![
1006 column_with_row_span(1, 3, vec![text("spans 3 rows")]),
1007 column_with_row_span(2, 1, vec![text("spans 2 cols")]),
1008 column(1, 1, vec![text("column4")]),
1009 ]),
1010 ParsedMarkdownTableRow::with_columns(vec![
1011 // First column covered by row span
1012 column(1, 1, vec![text("column2")]),
1013 column(1, 1, vec![text("column3")]),
1014 column(1, 1, vec![text("column4")]),
1015 ]),
1016 ParsedMarkdownTableRow::with_columns(vec![
1017 // First column still covered by row span
1018 column(3, 1, vec![text("spans 3 cols")]),
1019 ])
1020 ])
1021 );
1022 }
1023}