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