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