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, DefiniteLength, Div,
10 Element, ElementId, Entity, HighlightStyle, Hsla, ImageSource, InteractiveText, IntoElement,
11 Keystroke, Length, Modifiers, ParentElement, Render, Resource, SharedString, Styled,
12 StyledText, TextStyle, 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, relative, 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 element_background_color: Hsla,
55 text_color: Hsla,
56 link_color: Hsla,
57 window_rem_size: Pixels,
58 text_muted_color: Hsla,
59 code_block_background_color: Hsla,
60 code_span_background_color: Hsla,
61 syntax_theme: Arc<SyntaxTheme>,
62 indent: usize,
63 checkbox_clicked_callback: Option<CheckboxClickedCallback>,
64}
65
66impl RenderContext {
67 pub fn new(
68 workspace: Option<WeakEntity<Workspace>>,
69 window: &mut Window,
70 cx: &mut App,
71 ) -> RenderContext {
72 let theme = cx.theme().clone();
73
74 let settings = ThemeSettings::get_global(cx);
75 let buffer_font_family = settings.buffer_font.family.clone();
76 let mut buffer_text_style = window.text_style();
77 buffer_text_style.font_family = buffer_font_family.clone();
78 buffer_text_style.font_size = AbsoluteLength::from(settings.buffer_font_size(cx));
79
80 RenderContext {
81 workspace,
82 next_id: 0,
83 indent: 0,
84 buffer_font_family,
85 buffer_text_style,
86 text_style: window.text_style(),
87 syntax_theme: theme.syntax().clone(),
88 border_color: theme.colors().border,
89 element_background_color: theme.colors().element_background,
90 text_color: theme.colors().text,
91 link_color: theme.colors().text_accent,
92 window_rem_size: window.rem_size(),
93 text_muted_color: theme.colors().text_muted,
94 code_block_background_color: theme.colors().surface_background,
95 code_span_background_color: theme.colors().editor_document_highlight_read_background,
96 checkbox_clicked_callback: None,
97 }
98 }
99
100 pub fn with_checkbox_clicked_callback(
101 mut self,
102 callback: impl Fn(&CheckboxClickedEvent, &mut Window, &mut App) + 'static,
103 ) -> Self {
104 self.checkbox_clicked_callback = Some(Arc::new(Box::new(callback)));
105 self
106 }
107
108 fn next_id(&mut self, span: &Range<usize>) -> ElementId {
109 let id = format!("markdown-{}-{}-{}", self.next_id, span.start, span.end);
110 self.next_id += 1;
111 ElementId::from(SharedString::from(id))
112 }
113
114 /// HACK: used to have rems relative to buffer font size, so that things scale appropriately as
115 /// buffer font size changes. The callees of this function should be reimplemented to use real
116 /// relative sizing once that is implemented in GPUI
117 pub fn scaled_rems(&self, rems: f32) -> Rems {
118 self.buffer_text_style
119 .font_size
120 .to_rems(self.window_rem_size)
121 .mul(rems)
122 }
123
124 /// This ensures that children inside of block quotes
125 /// have padding between them.
126 ///
127 /// For example, for this markdown:
128 ///
129 /// ```markdown
130 /// > This is a block quote.
131 /// >
132 /// > And this is the next paragraph.
133 /// ```
134 ///
135 /// We give padding between "This is a block quote."
136 /// and "And this is the next paragraph."
137 fn with_common_p(&self, element: Div) -> Div {
138 if self.indent > 0 {
139 element.pb(self.scaled_rems(0.75))
140 } else {
141 element
142 }
143 }
144}
145
146pub fn render_parsed_markdown(
147 parsed: &ParsedMarkdown,
148 workspace: Option<WeakEntity<Workspace>>,
149 window: &mut Window,
150 cx: &mut App,
151) -> Div {
152 let mut cx = RenderContext::new(workspace, window, cx);
153
154 v_flex().gap_3().children(
155 parsed
156 .children
157 .iter()
158 .map(|block| render_markdown_block(block, &mut cx)),
159 )
160}
161pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
162 use ParsedMarkdownElement::*;
163 match block {
164 Paragraph(text) => render_markdown_paragraph(text, cx),
165 Heading(heading) => render_markdown_heading(heading, cx),
166 ListItem(list_item) => render_markdown_list_item(list_item, cx),
167 Table(table) => render_markdown_table(table, cx),
168 BlockQuote(block_quote) => render_markdown_block_quote(block_quote, cx),
169 CodeBlock(code_block) => render_markdown_code_block(code_block, cx),
170 HorizontalRule(_) => render_markdown_rule(cx),
171 Image(image) => render_markdown_image(image, cx),
172 }
173}
174
175fn render_markdown_heading(parsed: &ParsedMarkdownHeading, cx: &mut RenderContext) -> AnyElement {
176 let size = match parsed.level {
177 HeadingLevel::H1 => 2.,
178 HeadingLevel::H2 => 1.5,
179 HeadingLevel::H3 => 1.25,
180 HeadingLevel::H4 => 1.,
181 HeadingLevel::H5 => 0.875,
182 HeadingLevel::H6 => 0.85,
183 };
184
185 let text_size = cx.scaled_rems(size);
186
187 // was `DefiniteLength::from(text_size.mul(1.25))`
188 // let line_height = DefiniteLength::from(text_size.mul(1.25));
189 let line_height = text_size * 1.25;
190
191 // was `rems(0.15)`
192 // let padding_top = cx.scaled_rems(0.15);
193 let padding_top = rems(0.15);
194
195 // was `.pb_1()` = `rems(0.25)`
196 // let padding_bottom = cx.scaled_rems(0.25);
197 let padding_bottom = rems(0.25);
198
199 let color = match parsed.level {
200 HeadingLevel::H6 => cx.text_muted_color,
201 _ => cx.text_color,
202 };
203 div()
204 .line_height(line_height)
205 .text_size(text_size)
206 .text_color(color)
207 .pt(padding_top)
208 .pb(padding_bottom)
209 .children(render_markdown_text(&parsed.contents, cx))
210 .whitespace_normal()
211 .into_any()
212}
213
214fn render_markdown_list_item(
215 parsed: &ParsedMarkdownListItem,
216 cx: &mut RenderContext,
217) -> AnyElement {
218 use ParsedMarkdownListItemType::*;
219
220 let padding = cx.scaled_rems((parsed.depth - 1) as f32);
221
222 let bullet = match &parsed.item_type {
223 Ordered(order) => format!("{}.", order).into_any_element(),
224 Unordered => "•".into_any_element(),
225 Task(checked, range) => div()
226 .id(cx.next_id(range))
227 .mt(cx.scaled_rems(3.0 / 16.0))
228 .child(
229 MarkdownCheckbox::new(
230 "checkbox",
231 if *checked {
232 ToggleState::Selected
233 } else {
234 ToggleState::Unselected
235 },
236 cx.clone(),
237 )
238 .when_some(
239 cx.checkbox_clicked_callback.clone(),
240 |this, callback| {
241 this.on_click({
242 let range = range.clone();
243 move |selection, window, cx| {
244 let checked = match selection {
245 ToggleState::Selected => true,
246 ToggleState::Unselected => false,
247 _ => return,
248 };
249
250 if window.modifiers().secondary() {
251 callback(
252 &CheckboxClickedEvent {
253 checked,
254 source_range: range.clone(),
255 },
256 window,
257 cx,
258 );
259 }
260 }
261 })
262 },
263 ),
264 )
265 .hover(|s| s.cursor_pointer())
266 .tooltip(|_, cx| {
267 InteractiveMarkdownElementTooltip::new(None, "toggle checkbox", cx).into()
268 })
269 .into_any_element(),
270 };
271 let bullet = div().mr(cx.scaled_rems(0.5)).child(bullet);
272
273 let contents: Vec<AnyElement> = parsed
274 .content
275 .iter()
276 .map(|c| render_markdown_block(c, cx))
277 .collect();
278
279 let item = h_flex()
280 .pl(DefiniteLength::Absolute(AbsoluteLength::Rems(padding)))
281 .items_start()
282 .children(vec![
283 bullet,
284 v_flex()
285 .children(contents)
286 .gap(cx.scaled_rems(1.0))
287 .pr(cx.scaled_rems(1.0))
288 .w_full(),
289 ]);
290
291 cx.with_common_p(item).into_any()
292}
293
294/// # MarkdownCheckbox ///
295/// HACK: Copied from `ui/src/components/toggle.rs` to deal with scaling issues in markdown preview
296/// changes should be integrated into `Checkbox` in `toggle.rs` while making sure checkboxes elsewhere in the
297/// app are not visually affected
298#[derive(gpui::IntoElement)]
299struct MarkdownCheckbox {
300 id: ElementId,
301 toggle_state: ToggleState,
302 disabled: bool,
303 placeholder: bool,
304 on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
305 filled: bool,
306 style: ui::ToggleStyle,
307 tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
308 label: Option<SharedString>,
309 render_cx: RenderContext,
310}
311
312impl MarkdownCheckbox {
313 /// Creates a new [`Checkbox`].
314 fn new(id: impl Into<ElementId>, checked: ToggleState, render_cx: RenderContext) -> Self {
315 Self {
316 id: id.into(),
317 toggle_state: checked,
318 disabled: false,
319 on_click: None,
320 filled: false,
321 style: ui::ToggleStyle::default(),
322 tooltip: None,
323 label: None,
324 placeholder: false,
325 render_cx,
326 }
327 }
328
329 /// Binds a handler to the [`Checkbox`] that will be called when clicked.
330 fn on_click(mut self, handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static) -> Self {
331 self.on_click = Some(Box::new(handler));
332 self
333 }
334
335 fn bg_color(&self, cx: &App) -> Hsla {
336 let style = self.style.clone();
337 match (style, self.filled) {
338 (ui::ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
339 (ui::ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
340 (ui::ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
341 (ui::ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
342 (ui::ToggleStyle::Custom(_), false) => gpui::transparent_black(),
343 (ui::ToggleStyle::Custom(color), true) => color.opacity(0.2),
344 }
345 }
346
347 fn border_color(&self, cx: &App) -> Hsla {
348 if self.disabled {
349 return cx.theme().colors().border_variant;
350 }
351
352 match self.style.clone() {
353 ui::ToggleStyle::Ghost => cx.theme().colors().border,
354 ui::ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
355 ui::ToggleStyle::Custom(color) => color.opacity(0.3),
356 }
357 }
358}
359
360impl gpui::RenderOnce for MarkdownCheckbox {
361 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
362 let group_id = format!("checkbox_group_{:?}", self.id);
363 let color = if self.disabled {
364 Color::Disabled
365 } else {
366 Color::Selected
367 };
368 let icon_size_small = IconSize::Custom(self.render_cx.scaled_rems(14. / 16.)); // was IconSize::Small
369 let icon = match self.toggle_state {
370 ToggleState::Selected => {
371 if self.placeholder {
372 None
373 } else {
374 Some(
375 ui::Icon::new(IconName::Check)
376 .size(icon_size_small)
377 .color(color),
378 )
379 }
380 }
381 ToggleState::Indeterminate => Some(
382 ui::Icon::new(IconName::Dash)
383 .size(icon_size_small)
384 .color(color),
385 ),
386 ToggleState::Unselected => None,
387 };
388
389 let bg_color = self.bg_color(cx);
390 let border_color = self.border_color(cx);
391 let hover_border_color = border_color.alpha(0.7);
392
393 let size = self.render_cx.scaled_rems(1.25); // was Self::container_size(); (20px)
394
395 let checkbox = h_flex()
396 .id(self.id.clone())
397 .justify_center()
398 .items_center()
399 .size(size)
400 .group(group_id.clone())
401 .child(
402 div()
403 .flex()
404 .flex_none()
405 .justify_center()
406 .items_center()
407 .m(self.render_cx.scaled_rems(0.25)) // was .m_1
408 .size(self.render_cx.scaled_rems(1.0)) // was .size_4
409 .rounded(self.render_cx.scaled_rems(0.125)) // was .rounded_xs
410 .border_1()
411 .bg(bg_color)
412 .border_color(border_color)
413 .when(self.disabled, |this| this.cursor_not_allowed())
414 .when(self.disabled, |this| {
415 this.bg(cx.theme().colors().element_disabled.opacity(0.6))
416 })
417 .when(!self.disabled, |this| {
418 this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
419 })
420 .when(self.placeholder, |this| {
421 this.child(
422 div()
423 .flex_none()
424 .rounded_full()
425 .bg(color.color(cx).alpha(0.5))
426 .size(self.render_cx.scaled_rems(0.25)), // was .size_1
427 )
428 })
429 .children(icon),
430 );
431
432 h_flex()
433 .id(self.id)
434 .gap(ui::DynamicSpacing::Base06.rems(cx))
435 .child(checkbox)
436 .when_some(
437 self.on_click.filter(|_| !self.disabled),
438 |this, on_click| {
439 this.on_click(move |_, window, cx| {
440 on_click(&self.toggle_state.inverse(), window, cx)
441 })
442 },
443 )
444 // TODO: Allow label size to be different from default.
445 // TODO: Allow label color to be different from muted.
446 .when_some(self.label, |this, label| {
447 this.child(Label::new(label).color(Color::Muted))
448 })
449 .when_some(self.tooltip, |this, tooltip| {
450 this.tooltip(move |window, cx| tooltip(window, cx))
451 })
452 }
453}
454
455fn paragraph_len(paragraphs: &MarkdownParagraph) -> usize {
456 paragraphs
457 .iter()
458 .map(|paragraph| match paragraph {
459 MarkdownParagraphChunk::Text(text) => text.contents.len(),
460 // TODO: Scale column width based on image size
461 MarkdownParagraphChunk::Image(_) => 1,
462 })
463 .sum()
464}
465
466fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
467 let mut max_lengths: Vec<usize> = vec![0; parsed.header.children.len()];
468
469 for (index, cell) in parsed.header.children.iter().enumerate() {
470 let length = paragraph_len(cell);
471 max_lengths[index] = length;
472 }
473
474 for row in &parsed.body {
475 for (index, cell) in row.children.iter().enumerate() {
476 let length = paragraph_len(cell);
477
478 if index >= max_lengths.len() {
479 max_lengths.resize(index + 1, length);
480 }
481
482 if length > max_lengths[index] {
483 max_lengths[index] = length;
484 }
485 }
486 }
487
488 let total_max_length: usize = max_lengths.iter().sum();
489 let max_column_widths: Vec<f32> = max_lengths
490 .iter()
491 .map(|&length| length as f32 / total_max_length as f32)
492 .collect();
493
494 let header = render_markdown_table_row(
495 &parsed.header,
496 &parsed.column_alignments,
497 &max_column_widths,
498 true,
499 cx,
500 );
501
502 let body: Vec<AnyElement> = parsed
503 .body
504 .iter()
505 .map(|row| {
506 render_markdown_table_row(
507 row,
508 &parsed.column_alignments,
509 &max_column_widths,
510 false,
511 cx,
512 )
513 })
514 .collect();
515
516 cx.with_common_p(v_flex())
517 .w_full()
518 .child(header)
519 .children(body)
520 .into_any()
521}
522
523fn render_markdown_table_row(
524 parsed: &ParsedMarkdownTableRow,
525 alignments: &Vec<ParsedMarkdownTableAlignment>,
526 max_column_widths: &Vec<f32>,
527 is_header: bool,
528 cx: &mut RenderContext,
529) -> AnyElement {
530 let mut items = Vec::with_capacity(parsed.children.len());
531 let count = parsed.children.len();
532
533 for (index, cell) in parsed.children.iter().enumerate() {
534 let alignment = alignments
535 .get(index)
536 .copied()
537 .unwrap_or(ParsedMarkdownTableAlignment::None);
538
539 let contents = render_markdown_text(cell, cx);
540
541 let container = match alignment {
542 ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
543 ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
544 ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
545 };
546
547 let max_width = max_column_widths.get(index).unwrap_or(&0.0);
548 let mut cell = container
549 .w(Length::Definite(relative(*max_width)))
550 .h_full()
551 .children(contents)
552 .px_2()
553 .py_1()
554 .border_color(cx.border_color)
555 .border_l_1();
556
557 if count == index + 1 {
558 cell = cell.border_r_1();
559 }
560
561 if is_header {
562 cell = cell.bg(cx.element_background_color)
563 }
564
565 items.push(cell);
566 }
567
568 let mut row = h_flex().border_color(cx.border_color);
569
570 if is_header {
571 row = row.border_y_1();
572 } else {
573 row = row.border_b_1();
574 }
575
576 row.children(items).into_any_element()
577}
578
579fn render_markdown_block_quote(
580 parsed: &ParsedMarkdownBlockQuote,
581 cx: &mut RenderContext,
582) -> AnyElement {
583 cx.indent += 1;
584
585 let children: Vec<AnyElement> = parsed
586 .children
587 .iter()
588 .map(|child| render_markdown_block(child, cx))
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, link_color)
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 {
689 None
690 }
691 },
692 ),
693 );
694 let mut links = Vec::new();
695 let mut link_ranges = Vec::new();
696 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
697 if let Some(link) = region.link.clone() {
698 links.push(link);
699 link_ranges.push(range.clone());
700 }
701 }
702 let workspace = workspace_clone.clone();
703 let element = div()
704 .child(
705 InteractiveText::new(
706 element_id,
707 StyledText::new(parsed.contents.clone())
708 .with_default_highlights(&text_style, highlights),
709 )
710 .tooltip({
711 let links = links.clone();
712 let link_ranges = link_ranges.clone();
713 move |idx, _, cx| {
714 for (ix, range) in link_ranges.iter().enumerate() {
715 if range.contains(&idx) {
716 return Some(LinkPreview::new(&links[ix].to_string(), cx));
717 }
718 }
719 None
720 }
721 })
722 .on_click(
723 link_ranges,
724 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
725 Link::Web { url } => cx.open_url(url),
726 Link::Path { path, .. } => {
727 if let Some(workspace) = &workspace {
728 _ = workspace.update(cx, |workspace, cx| {
729 workspace
730 .open_abs_path(
731 normalize_path(path.clone().as_path()),
732 OpenOptions {
733 visible: Some(OpenVisible::None),
734 ..Default::default()
735 },
736 window,
737 cx,
738 )
739 .detach();
740 });
741 }
742 }
743 },
744 ),
745 )
746 .into_any();
747 any_element.push(element);
748 }
749
750 MarkdownParagraphChunk::Image(image) => {
751 any_element.push(render_markdown_image(image, cx));
752 }
753 }
754 }
755
756 any_element
757}
758
759fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
760 let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
761 div().py(cx.scaled_rems(0.5)).child(rule).into_any()
762}
763
764fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
765 let image_resource = match image.link.clone() {
766 Link::Web { url } => Resource::Uri(url.into()),
767 Link::Path { path, .. } => Resource::Path(Arc::from(path)),
768 };
769
770 let element_id = cx.next_id(&image.source_range);
771 let workspace = cx.workspace.clone();
772
773 div()
774 .id(element_id)
775 .cursor_pointer()
776 .child(
777 img(ImageSource::Resource(image_resource))
778 .max_w_full()
779 .with_fallback({
780 let alt_text = image.alt_text.clone();
781 move || div().children(alt_text.clone()).into_any_element()
782 })
783 .when_some(image.height, |this, height| this.h(height))
784 .when_some(image.width, |this, width| this.w(width)),
785 )
786 .tooltip({
787 let link = image.link.clone();
788 let alt_text = image.alt_text.clone();
789 move |_, cx| {
790 InteractiveMarkdownElementTooltip::new(
791 Some(alt_text.clone().unwrap_or(link.to_string().into())),
792 "open image",
793 cx,
794 )
795 .into()
796 }
797 })
798 .on_click({
799 let link = image.link.clone();
800 move |_, window, cx| {
801 if window.modifiers().secondary() {
802 match &link {
803 Link::Web { url } => cx.open_url(url),
804 Link::Path { path, .. } => {
805 if let Some(workspace) = &workspace {
806 _ = workspace.update(cx, |workspace, cx| {
807 workspace
808 .open_abs_path(
809 path.clone(),
810 OpenOptions {
811 visible: Some(OpenVisible::None),
812 ..Default::default()
813 },
814 window,
815 cx,
816 )
817 .detach();
818 });
819 }
820 }
821 }
822 }
823 }
824 })
825 .into_any()
826}
827
828struct InteractiveMarkdownElementTooltip {
829 tooltip_text: Option<SharedString>,
830 action_text: SharedString,
831}
832
833impl InteractiveMarkdownElementTooltip {
834 pub fn new(
835 tooltip_text: Option<SharedString>,
836 action_text: impl Into<SharedString>,
837 cx: &mut App,
838 ) -> Entity<Self> {
839 let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
840
841 cx.new(|_cx| Self {
842 tooltip_text,
843 action_text: action_text.into(),
844 })
845 }
846}
847
848impl Render for InteractiveMarkdownElementTooltip {
849 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
850 tooltip_container(cx, |el, _| {
851 let secondary_modifier = Keystroke {
852 modifiers: Modifiers::secondary_key(),
853 ..Default::default()
854 };
855
856 el.child(
857 v_flex()
858 .gap_1()
859 .when_some(self.tooltip_text.clone(), |this, text| {
860 this.child(Label::new(text).size(LabelSize::Small))
861 })
862 .child(
863 Label::new(format!(
864 "{}-click to {}",
865 secondary_modifier, self.action_text
866 ))
867 .size(LabelSize::Small)
868 .color(Color::Muted),
869 ),
870 )
871 })
872 }
873}