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 length > max_lengths[index] {
479 max_lengths[index] = length;
480 }
481 }
482 }
483
484 let total_max_length: usize = max_lengths.iter().sum();
485 let max_column_widths: Vec<f32> = max_lengths
486 .iter()
487 .map(|&length| length as f32 / total_max_length as f32)
488 .collect();
489
490 let header = render_markdown_table_row(
491 &parsed.header,
492 &parsed.column_alignments,
493 &max_column_widths,
494 true,
495 cx,
496 );
497
498 let body: Vec<AnyElement> = parsed
499 .body
500 .iter()
501 .map(|row| {
502 render_markdown_table_row(
503 row,
504 &parsed.column_alignments,
505 &max_column_widths,
506 false,
507 cx,
508 )
509 })
510 .collect();
511
512 cx.with_common_p(v_flex())
513 .w_full()
514 .child(header)
515 .children(body)
516 .into_any()
517}
518
519fn render_markdown_table_row(
520 parsed: &ParsedMarkdownTableRow,
521 alignments: &Vec<ParsedMarkdownTableAlignment>,
522 max_column_widths: &Vec<f32>,
523 is_header: bool,
524 cx: &mut RenderContext,
525) -> AnyElement {
526 let mut items = vec![];
527 let count = parsed.children.len();
528
529 for (index, cell) in parsed.children.iter().enumerate() {
530 let alignment = alignments
531 .get(index)
532 .copied()
533 .unwrap_or(ParsedMarkdownTableAlignment::None);
534
535 let contents = render_markdown_text(cell, cx);
536
537 let container = match alignment {
538 ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
539 ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
540 ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
541 };
542
543 let max_width = max_column_widths.get(index).unwrap_or(&0.0);
544 let mut cell = container
545 .w(Length::Definite(relative(*max_width)))
546 .h_full()
547 .children(contents)
548 .px_2()
549 .py_1()
550 .border_color(cx.border_color)
551 .border_l_1();
552
553 if count == index + 1 {
554 cell = cell.border_r_1();
555 }
556
557 if is_header {
558 cell = cell.bg(cx.element_background_color)
559 }
560
561 items.push(cell);
562 }
563
564 let mut row = h_flex().border_color(cx.border_color);
565
566 if is_header {
567 row = row.border_y_1();
568 } else {
569 row = row.border_b_1();
570 }
571
572 row.children(items).into_any_element()
573}
574
575fn render_markdown_block_quote(
576 parsed: &ParsedMarkdownBlockQuote,
577 cx: &mut RenderContext,
578) -> AnyElement {
579 cx.indent += 1;
580
581 let children: Vec<AnyElement> = parsed
582 .children
583 .iter()
584 .map(|child| render_markdown_block(child, cx))
585 .collect();
586
587 cx.indent -= 1;
588
589 cx.with_common_p(div())
590 .child(
591 div()
592 .border_l_4()
593 .border_color(cx.border_color)
594 .pl_3()
595 .children(children),
596 )
597 .into_any()
598}
599
600fn render_markdown_code_block(
601 parsed: &ParsedMarkdownCodeBlock,
602 cx: &mut RenderContext,
603) -> AnyElement {
604 let body = if let Some(highlights) = parsed.highlights.as_ref() {
605 StyledText::new(parsed.contents.clone()).with_default_highlights(
606 &cx.buffer_text_style,
607 highlights.iter().filter_map(|(range, highlight_id)| {
608 highlight_id
609 .style(cx.syntax_theme.as_ref())
610 .map(|style| (range.clone(), style))
611 }),
612 )
613 } else {
614 StyledText::new(parsed.contents.clone())
615 };
616
617 let copy_block_button = IconButton::new("copy-code", IconName::Copy)
618 .icon_size(IconSize::Small)
619 .on_click({
620 let contents = parsed.contents.clone();
621 move |_, _window, cx| {
622 cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
623 }
624 })
625 .tooltip(Tooltip::text("Copy code block"))
626 .visible_on_hover("markdown-block");
627
628 cx.with_common_p(div())
629 .font_family(cx.buffer_font_family.clone())
630 .px_3()
631 .py_3()
632 .bg(cx.code_block_background_color)
633 .rounded_sm()
634 .child(body)
635 .child(
636 div()
637 .h_flex()
638 .absolute()
639 .right_1()
640 .top_1()
641 .child(copy_block_button),
642 )
643 .into_any()
644}
645
646fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
647 cx.with_common_p(div())
648 .children(render_markdown_text(parsed, cx))
649 .flex()
650 .flex_col()
651 .into_any_element()
652}
653
654fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
655 let mut any_element = vec![];
656 // these values are cloned in-order satisfy borrow checker
657 let syntax_theme = cx.syntax_theme.clone();
658 let workspace_clone = cx.workspace.clone();
659 let code_span_bg_color = cx.code_span_background_color;
660 let text_style = cx.text_style.clone();
661 let link_color = cx.link_color;
662
663 for parsed_region in parsed_new {
664 match parsed_region {
665 MarkdownParagraphChunk::Text(parsed) => {
666 let element_id = cx.next_id(&parsed.source_range);
667
668 let highlights = gpui::combine_highlights(
669 parsed.highlights.iter().filter_map(|(range, highlight)| {
670 highlight
671 .to_highlight_style(&syntax_theme, link_color)
672 .map(|style| (range.clone(), style))
673 }),
674 parsed.regions.iter().zip(&parsed.region_ranges).filter_map(
675 |(region, range)| {
676 if region.code {
677 Some((
678 range.clone(),
679 HighlightStyle {
680 background_color: Some(code_span_bg_color),
681 ..Default::default()
682 },
683 ))
684 } else {
685 None
686 }
687 },
688 ),
689 );
690 let mut links = Vec::new();
691 let mut link_ranges = Vec::new();
692 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
693 if let Some(link) = region.link.clone() {
694 links.push(link);
695 link_ranges.push(range.clone());
696 }
697 }
698 let workspace = workspace_clone.clone();
699 let element = div()
700 .child(
701 InteractiveText::new(
702 element_id,
703 StyledText::new(parsed.contents.clone())
704 .with_default_highlights(&text_style, highlights),
705 )
706 .tooltip({
707 let links = links.clone();
708 let link_ranges = link_ranges.clone();
709 move |idx, _, cx| {
710 for (ix, range) in link_ranges.iter().enumerate() {
711 if range.contains(&idx) {
712 return Some(LinkPreview::new(&links[ix].to_string(), cx));
713 }
714 }
715 None
716 }
717 })
718 .on_click(
719 link_ranges,
720 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
721 Link::Web { url } => cx.open_url(url),
722 Link::Path { path, .. } => {
723 if let Some(workspace) = &workspace {
724 _ = workspace.update(cx, |workspace, cx| {
725 workspace
726 .open_abs_path(
727 normalize_path(path.clone().as_path()),
728 OpenOptions {
729 visible: Some(OpenVisible::None),
730 ..Default::default()
731 },
732 window,
733 cx,
734 )
735 .detach();
736 });
737 }
738 }
739 },
740 ),
741 )
742 .into_any();
743 any_element.push(element);
744 }
745
746 MarkdownParagraphChunk::Image(image) => {
747 any_element.push(render_markdown_image(image, cx));
748 }
749 }
750 }
751
752 any_element
753}
754
755fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
756 let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
757 div().py(cx.scaled_rems(0.5)).child(rule).into_any()
758}
759
760fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
761 let image_resource = match image.link.clone() {
762 Link::Web { url } => Resource::Uri(url.into()),
763 Link::Path { path, .. } => Resource::Path(Arc::from(path)),
764 };
765
766 let element_id = cx.next_id(&image.source_range);
767 let workspace = cx.workspace.clone();
768
769 div()
770 .id(element_id)
771 .cursor_pointer()
772 .child(
773 img(ImageSource::Resource(image_resource))
774 .max_w_full()
775 .with_fallback({
776 let alt_text = image.alt_text.clone();
777 move || div().children(alt_text.clone()).into_any_element()
778 })
779 .when_some(image.height, |this, height| this.h(height))
780 .when_some(image.width, |this, width| this.w(width)),
781 )
782 .tooltip({
783 let link = image.link.clone();
784 let alt_text = image.alt_text.clone();
785 move |_, cx| {
786 InteractiveMarkdownElementTooltip::new(
787 Some(alt_text.clone().unwrap_or(link.to_string().into())),
788 "open image",
789 cx,
790 )
791 .into()
792 }
793 })
794 .on_click({
795 let link = image.link.clone();
796 move |_, window, cx| {
797 if window.modifiers().secondary() {
798 match &link {
799 Link::Web { url } => cx.open_url(url),
800 Link::Path { path, .. } => {
801 if let Some(workspace) = &workspace {
802 _ = workspace.update(cx, |workspace, cx| {
803 workspace
804 .open_abs_path(
805 path.clone(),
806 OpenOptions {
807 visible: Some(OpenVisible::None),
808 ..Default::default()
809 },
810 window,
811 cx,
812 )
813 .detach();
814 });
815 }
816 }
817 }
818 }
819 }
820 })
821 .into_any()
822}
823
824struct InteractiveMarkdownElementTooltip {
825 tooltip_text: Option<SharedString>,
826 action_text: SharedString,
827}
828
829impl InteractiveMarkdownElementTooltip {
830 pub fn new(
831 tooltip_text: Option<SharedString>,
832 action_text: impl Into<SharedString>,
833 cx: &mut App,
834 ) -> Entity<Self> {
835 let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
836
837 cx.new(|_cx| Self {
838 tooltip_text,
839 action_text: action_text.into(),
840 })
841 }
842}
843
844impl Render for InteractiveMarkdownElementTooltip {
845 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
846 tooltip_container(cx, |el, _| {
847 let secondary_modifier = Keystroke {
848 modifiers: Modifiers::secondary_key(),
849 ..Default::default()
850 };
851
852 el.child(
853 v_flex()
854 .gap_1()
855 .when_some(self.tooltip_text.clone(), |this, text| {
856 this.child(Label::new(text).size(LabelSize::Small))
857 })
858 .child(
859 Label::new(format!(
860 "{}-click to {}",
861 secondary_modifier, self.action_text
862 ))
863 .size(LabelSize::Small)
864 .color(Color::Muted),
865 ),
866 )
867 })
868 }
869}