1use crate::markdown_elements::{
2 HeadingLevel, Image, Link, MarkdownParagraph, MarkdownParagraphChunk, ParsedMarkdown,
3 ParsedMarkdownBlockQuote, ParsedMarkdownCodeBlock, ParsedMarkdownElement,
4 ParsedMarkdownHeading, ParsedMarkdownListItem, ParsedMarkdownListItemType, ParsedMarkdownTable,
5 ParsedMarkdownTableAlignment, ParsedMarkdownTableRow,
6};
7use fs::normalize_path;
8use gpui::{
9 AbsoluteLength, AnyElement, App, AppContext as _, ClipboardItem, Context, Div, Element,
10 ElementId, Entity, HighlightStyle, Hsla, ImageSource, InteractiveText, IntoElement, Keystroke,
11 Modifiers, ParentElement, Render, Resource, SharedString, Styled, StyledText, TextStyle,
12 WeakEntity, Window, div, img, px, rems,
13};
14use settings::Settings;
15use std::{
16 ops::{Mul, Range},
17 sync::Arc,
18 vec,
19};
20use theme::{ActiveTheme, SyntaxTheme, ThemeSettings};
21use ui::{
22 ButtonCommon, Clickable, Color, FluentBuilder, IconButton, IconName, IconSize,
23 InteractiveElement, Label, LabelCommon, LabelSize, LinkPreview, Pixels, Rems,
24 StatefulInteractiveElement, StyledExt, StyledImage, ToggleState, Tooltip, VisibleOnHover,
25 h_flex, tooltip_container, v_flex,
26};
27use workspace::{OpenOptions, OpenVisible, Workspace};
28
29pub struct CheckboxClickedEvent {
30 pub checked: bool,
31 pub source_range: Range<usize>,
32}
33
34impl CheckboxClickedEvent {
35 pub fn source_range(&self) -> Range<usize> {
36 self.source_range.clone()
37 }
38
39 pub fn checked(&self) -> bool {
40 self.checked
41 }
42}
43
44type CheckboxClickedCallback = Arc<Box<dyn Fn(&CheckboxClickedEvent, &mut Window, &mut App)>>;
45
46#[derive(Clone)]
47pub struct RenderContext {
48 workspace: Option<WeakEntity<Workspace>>,
49 next_id: usize,
50 buffer_font_family: SharedString,
51 buffer_text_style: TextStyle,
52 text_style: TextStyle,
53 border_color: Hsla,
54 title_bar_background_color: Hsla,
55 panel_background_color: Hsla,
56 text_color: Hsla,
57 link_color: Hsla,
58 window_rem_size: Pixels,
59 text_muted_color: Hsla,
60 code_block_background_color: Hsla,
61 code_span_background_color: Hsla,
62 syntax_theme: Arc<SyntaxTheme>,
63 indent: usize,
64 checkbox_clicked_callback: Option<CheckboxClickedCallback>,
65 is_last_child: bool,
66}
67
68impl RenderContext {
69 pub fn new(
70 workspace: Option<WeakEntity<Workspace>>,
71 window: &mut Window,
72 cx: &mut App,
73 ) -> RenderContext {
74 let theme = cx.theme().clone();
75
76 let settings = ThemeSettings::get_global(cx);
77 let buffer_font_family = settings.buffer_font.family.clone();
78 let buffer_font_features = settings.buffer_font.features.clone();
79 let mut buffer_text_style = window.text_style();
80 buffer_text_style.font_family = buffer_font_family.clone();
81 buffer_text_style.font_features = buffer_font_features;
82 buffer_text_style.font_size = AbsoluteLength::from(settings.buffer_font_size(cx));
83
84 RenderContext {
85 workspace,
86 next_id: 0,
87 indent: 0,
88 buffer_font_family,
89 buffer_text_style,
90 text_style: window.text_style(),
91 syntax_theme: theme.syntax().clone(),
92 border_color: theme.colors().border,
93 title_bar_background_color: theme.colors().title_bar_background,
94 panel_background_color: theme.colors().panel_background,
95 text_color: theme.colors().text,
96 link_color: theme.colors().text_accent,
97 window_rem_size: window.rem_size(),
98 text_muted_color: theme.colors().text_muted,
99 code_block_background_color: theme.colors().surface_background,
100 code_span_background_color: theme.colors().editor_document_highlight_read_background,
101 checkbox_clicked_callback: None,
102 is_last_child: false,
103 }
104 }
105
106 pub fn with_checkbox_clicked_callback(
107 mut self,
108 callback: impl Fn(&CheckboxClickedEvent, &mut Window, &mut App) + 'static,
109 ) -> Self {
110 self.checkbox_clicked_callback = Some(Arc::new(Box::new(callback)));
111 self
112 }
113
114 fn next_id(&mut self, span: &Range<usize>) -> ElementId {
115 let id = format!("markdown-{}-{}-{}", self.next_id, span.start, span.end);
116 self.next_id += 1;
117 ElementId::from(SharedString::from(id))
118 }
119
120 /// HACK: used to have rems relative to buffer font size, so that things scale appropriately as
121 /// buffer font size changes. The callees of this function should be reimplemented to use real
122 /// relative sizing once that is implemented in GPUI
123 pub fn scaled_rems(&self, rems: f32) -> Rems {
124 self.buffer_text_style
125 .font_size
126 .to_rems(self.window_rem_size)
127 .mul(rems)
128 }
129
130 /// This ensures that children inside of block quotes
131 /// have padding between them.
132 ///
133 /// For example, for this markdown:
134 ///
135 /// ```markdown
136 /// > This is a block quote.
137 /// >
138 /// > And this is the next paragraph.
139 /// ```
140 ///
141 /// We give padding between "This is a block quote."
142 /// and "And this is the next paragraph."
143 fn with_common_p(&self, element: Div) -> Div {
144 if self.indent > 0 && !self.is_last_child {
145 element.pb(self.scaled_rems(0.75))
146 } else {
147 element
148 }
149 }
150
151 /// The is used to indicate that the current element is the last child or not of its parent.
152 ///
153 /// Then we can avoid adding padding to the bottom of the last child.
154 fn with_last_child<R>(&mut self, is_last: bool, render: R) -> AnyElement
155 where
156 R: FnOnce(&mut Self) -> AnyElement,
157 {
158 self.is_last_child = is_last;
159 let element = render(self);
160 self.is_last_child = false;
161 element
162 }
163}
164
165pub fn render_parsed_markdown(
166 parsed: &ParsedMarkdown,
167 workspace: Option<WeakEntity<Workspace>>,
168 window: &mut Window,
169 cx: &mut App,
170) -> Div {
171 let mut cx = RenderContext::new(workspace, window, cx);
172
173 v_flex().gap_3().children(
174 parsed
175 .children
176 .iter()
177 .map(|block| render_markdown_block(block, &mut cx)),
178 )
179}
180pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
181 use ParsedMarkdownElement::*;
182 match block {
183 Paragraph(text) => render_markdown_paragraph(text, cx),
184 Heading(heading) => render_markdown_heading(heading, cx),
185 ListItem(list_item) => render_markdown_list_item(list_item, cx),
186 Table(table) => render_markdown_table(table, cx),
187 BlockQuote(block_quote) => render_markdown_block_quote(block_quote, cx),
188 CodeBlock(code_block) => render_markdown_code_block(code_block, cx),
189 HorizontalRule(_) => render_markdown_rule(cx),
190 Image(image) => render_markdown_image(image, cx),
191 }
192}
193
194fn render_markdown_heading(parsed: &ParsedMarkdownHeading, cx: &mut RenderContext) -> AnyElement {
195 let size = match parsed.level {
196 HeadingLevel::H1 => 2.,
197 HeadingLevel::H2 => 1.5,
198 HeadingLevel::H3 => 1.25,
199 HeadingLevel::H4 => 1.,
200 HeadingLevel::H5 => 0.875,
201 HeadingLevel::H6 => 0.85,
202 };
203
204 let text_size = cx.scaled_rems(size);
205
206 // was `DefiniteLength::from(text_size.mul(1.25))`
207 // let line_height = DefiniteLength::from(text_size.mul(1.25));
208 let line_height = text_size * 1.25;
209
210 // was `rems(0.15)`
211 // let padding_top = cx.scaled_rems(0.15);
212 let padding_top = rems(0.15);
213
214 // was `.pb_1()` = `rems(0.25)`
215 // let padding_bottom = cx.scaled_rems(0.25);
216 let padding_bottom = rems(0.25);
217
218 let color = match parsed.level {
219 HeadingLevel::H6 => cx.text_muted_color,
220 _ => cx.text_color,
221 };
222 div()
223 .line_height(line_height)
224 .text_size(text_size)
225 .text_color(color)
226 .pt(padding_top)
227 .pb(padding_bottom)
228 .children(render_markdown_text(&parsed.contents, cx))
229 .whitespace_normal()
230 .into_any()
231}
232
233fn render_markdown_list_item(
234 parsed: &ParsedMarkdownListItem,
235 cx: &mut RenderContext,
236) -> AnyElement {
237 use ParsedMarkdownListItemType::*;
238 let depth = parsed.depth.saturating_sub(1) as usize;
239
240 let bullet = match &parsed.item_type {
241 Ordered(order) => list_item_prefix(*order as usize, true, depth).into_any_element(),
242 Unordered => list_item_prefix(1, false, depth).into_any_element(),
243 Task(checked, range) => div()
244 .id(cx.next_id(range))
245 .mt(cx.scaled_rems(3.0 / 16.0))
246 .child(
247 MarkdownCheckbox::new(
248 "checkbox",
249 if *checked {
250 ToggleState::Selected
251 } else {
252 ToggleState::Unselected
253 },
254 cx.clone(),
255 )
256 .when_some(
257 cx.checkbox_clicked_callback.clone(),
258 |this, callback| {
259 this.on_click({
260 let range = range.clone();
261 move |selection, window, cx| {
262 let checked = match selection {
263 ToggleState::Selected => true,
264 ToggleState::Unselected => false,
265 _ => return,
266 };
267
268 if window.modifiers().secondary() {
269 callback(
270 &CheckboxClickedEvent {
271 checked,
272 source_range: range.clone(),
273 },
274 window,
275 cx,
276 );
277 }
278 }
279 })
280 },
281 ),
282 )
283 .hover(|s| s.cursor_pointer())
284 .tooltip(|_, cx| {
285 InteractiveMarkdownElementTooltip::new(None, "toggle checkbox", cx).into()
286 })
287 .into_any_element(),
288 };
289 let bullet = div().mr(cx.scaled_rems(0.5)).child(bullet);
290
291 let contents: Vec<AnyElement> = parsed
292 .content
293 .iter()
294 .map(|c| render_markdown_block(c, cx))
295 .collect();
296
297 let item = h_flex()
298 .when(!parsed.nested, |this| this.pl(cx.scaled_rems(depth as f32)))
299 .when(parsed.nested && depth > 0, |this| this.ml_neg_1p5())
300 .items_start()
301 .children(vec![
302 bullet,
303 v_flex()
304 .children(contents)
305 .when(!parsed.nested, |this| this.gap(cx.scaled_rems(1.0)))
306 .pr(cx.scaled_rems(1.0))
307 .w_full(),
308 ]);
309
310 cx.with_common_p(item).into_any()
311}
312
313/// # MarkdownCheckbox ///
314/// HACK: Copied from `ui/src/components/toggle.rs` to deal with scaling issues in markdown preview
315/// changes should be integrated into `Checkbox` in `toggle.rs` while making sure checkboxes elsewhere in the
316/// app are not visually affected
317#[derive(gpui::IntoElement)]
318struct MarkdownCheckbox {
319 id: ElementId,
320 toggle_state: ToggleState,
321 disabled: bool,
322 placeholder: bool,
323 on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
324 filled: bool,
325 style: ui::ToggleStyle,
326 tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
327 label: Option<SharedString>,
328 render_cx: RenderContext,
329}
330
331impl MarkdownCheckbox {
332 /// Creates a new [`Checkbox`].
333 fn new(id: impl Into<ElementId>, checked: ToggleState, render_cx: RenderContext) -> Self {
334 Self {
335 id: id.into(),
336 toggle_state: checked,
337 disabled: false,
338 on_click: None,
339 filled: false,
340 style: ui::ToggleStyle::default(),
341 tooltip: None,
342 label: None,
343 placeholder: false,
344 render_cx,
345 }
346 }
347
348 /// Binds a handler to the [`Checkbox`] that will be called when clicked.
349 fn on_click(mut self, handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static) -> Self {
350 self.on_click = Some(Box::new(handler));
351 self
352 }
353
354 fn bg_color(&self, cx: &App) -> Hsla {
355 let style = self.style.clone();
356 match (style, self.filled) {
357 (ui::ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
358 (ui::ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
359 (ui::ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
360 (ui::ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
361 (ui::ToggleStyle::Custom(_), false) => gpui::transparent_black(),
362 (ui::ToggleStyle::Custom(color), true) => color.opacity(0.2),
363 }
364 }
365
366 fn border_color(&self, cx: &App) -> Hsla {
367 if self.disabled {
368 return cx.theme().colors().border_variant;
369 }
370
371 match self.style.clone() {
372 ui::ToggleStyle::Ghost => cx.theme().colors().border,
373 ui::ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
374 ui::ToggleStyle::Custom(color) => color.opacity(0.3),
375 }
376 }
377}
378
379impl gpui::RenderOnce for MarkdownCheckbox {
380 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
381 let group_id = format!("checkbox_group_{:?}", self.id);
382 let color = if self.disabled {
383 Color::Disabled
384 } else {
385 Color::Selected
386 };
387 let icon_size_small = IconSize::Custom(self.render_cx.scaled_rems(14. / 16.)); // was IconSize::Small
388 let icon = match self.toggle_state {
389 ToggleState::Selected => {
390 if self.placeholder {
391 None
392 } else {
393 Some(
394 ui::Icon::new(IconName::Check)
395 .size(icon_size_small)
396 .color(color),
397 )
398 }
399 }
400 ToggleState::Indeterminate => Some(
401 ui::Icon::new(IconName::Dash)
402 .size(icon_size_small)
403 .color(color),
404 ),
405 ToggleState::Unselected => None,
406 };
407
408 let bg_color = self.bg_color(cx);
409 let border_color = self.border_color(cx);
410 let hover_border_color = border_color.alpha(0.7);
411
412 let size = self.render_cx.scaled_rems(1.25); // was Self::container_size(); (20px)
413
414 let checkbox = h_flex()
415 .id(self.id.clone())
416 .justify_center()
417 .items_center()
418 .size(size)
419 .group(group_id.clone())
420 .child(
421 div()
422 .flex()
423 .flex_none()
424 .justify_center()
425 .items_center()
426 .m(self.render_cx.scaled_rems(0.25)) // was .m_1
427 .size(self.render_cx.scaled_rems(1.0)) // was .size_4
428 .rounded(self.render_cx.scaled_rems(0.125)) // was .rounded_xs
429 .border_1()
430 .bg(bg_color)
431 .border_color(border_color)
432 .when(self.disabled, |this| this.cursor_not_allowed())
433 .when(self.disabled, |this| {
434 this.bg(cx.theme().colors().element_disabled.opacity(0.6))
435 })
436 .when(!self.disabled, |this| {
437 this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
438 })
439 .when(self.placeholder, |this| {
440 this.child(
441 div()
442 .flex_none()
443 .rounded_full()
444 .bg(color.color(cx).alpha(0.5))
445 .size(self.render_cx.scaled_rems(0.25)), // was .size_1
446 )
447 })
448 .children(icon),
449 );
450
451 h_flex()
452 .id(self.id)
453 .gap(ui::DynamicSpacing::Base06.rems(cx))
454 .child(checkbox)
455 .when_some(
456 self.on_click.filter(|_| !self.disabled),
457 |this, on_click| {
458 this.on_click(move |_, window, cx| {
459 on_click(&self.toggle_state.inverse(), window, cx)
460 })
461 },
462 )
463 // TODO: Allow label size to be different from default.
464 // TODO: Allow label color to be different from muted.
465 .when_some(self.label, |this, label| {
466 this.child(Label::new(label).color(Color::Muted))
467 })
468 .when_some(self.tooltip, |this, tooltip| {
469 this.tooltip(move |window, cx| tooltip(window, cx))
470 })
471 }
472}
473
474fn calculate_table_columns_count(rows: &Vec<ParsedMarkdownTableRow>) -> usize {
475 let mut actual_column_count = 0;
476 for row in rows {
477 actual_column_count = actual_column_count.max(
478 row.columns
479 .iter()
480 .map(|column| column.col_span)
481 .sum::<usize>(),
482 );
483 }
484 actual_column_count
485}
486
487fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -> AnyElement {
488 let actual_header_column_count = calculate_table_columns_count(&parsed.header);
489 let actual_body_column_count = calculate_table_columns_count(&parsed.body);
490 let max_column_count = std::cmp::max(actual_header_column_count, actual_body_column_count);
491
492 let total_rows = parsed.header.len() + parsed.body.len();
493
494 // Track which grid cells are occupied by spanning cells
495 let mut grid_occupied = vec![vec![false; max_column_count]; total_rows];
496
497 let mut cells = Vec::with_capacity(total_rows * max_column_count);
498
499 for (row_idx, row) in parsed.header.iter().chain(parsed.body.iter()).enumerate() {
500 let mut col_idx = 0;
501
502 for cell in row.columns.iter() {
503 // Skip columns occupied by row-spanning cells from previous rows
504 while col_idx < max_column_count && grid_occupied[row_idx][col_idx] {
505 col_idx += 1;
506 }
507
508 if col_idx >= max_column_count {
509 break;
510 }
511
512 let container = match cell.alignment {
513 ParsedMarkdownTableAlignment::Left | ParsedMarkdownTableAlignment::None => div(),
514 ParsedMarkdownTableAlignment::Center => v_flex().items_center(),
515 ParsedMarkdownTableAlignment::Right => v_flex().items_end(),
516 };
517
518 let cell_element = container
519 .col_span(cell.col_span.min(max_column_count - col_idx) as u16)
520 .row_span(cell.row_span.min(total_rows - row_idx) as u16)
521 .children(render_markdown_text(&cell.children, cx))
522 .px_2()
523 .py_1()
524 .when(col_idx > 0, |this| this.border_l_1())
525 .when(row_idx > 0, |this| this.border_t_1())
526 .border_color(cx.border_color)
527 .when(cell.is_header, |this| {
528 this.bg(cx.title_bar_background_color)
529 })
530 .when(cell.row_span > 1, |this| this.justify_center())
531 .when(row_idx % 2 == 1, |this| this.bg(cx.panel_background_color));
532
533 cells.push(cell_element);
534
535 // Mark grid positions as occupied for row-spanning cells
536 for r in 0..cell.row_span {
537 for c in 0..cell.col_span {
538 if row_idx + r < total_rows && col_idx + c < max_column_count {
539 grid_occupied[row_idx + r][col_idx + c] = true;
540 }
541 }
542 }
543
544 col_idx += cell.col_span;
545 }
546
547 // Fill remaining columns with empty cells if needed
548 while col_idx < max_column_count {
549 if grid_occupied[row_idx][col_idx] {
550 col_idx += 1;
551 continue;
552 }
553
554 let empty_cell = div()
555 .when(col_idx > 0, |this| this.border_l_1())
556 .when(row_idx > 0, |this| this.border_t_1())
557 .border_color(cx.border_color)
558 .when(row_idx % 2 == 1, |this| this.bg(cx.panel_background_color));
559
560 cells.push(empty_cell);
561 col_idx += 1;
562 }
563 }
564
565 cx.with_common_p(v_flex().items_start())
566 .when_some(parsed.caption.as_ref(), |this, caption| {
567 this.children(render_markdown_text(caption, cx))
568 })
569 .child(
570 div()
571 .grid()
572 .grid_cols(max_column_count as u16)
573 .border(px(1.5))
574 .border_color(cx.border_color)
575 .rounded_sm()
576 .overflow_hidden()
577 .children(cells),
578 )
579 .into_any()
580}
581
582fn render_markdown_block_quote(
583 parsed: &ParsedMarkdownBlockQuote,
584 cx: &mut RenderContext,
585) -> AnyElement {
586 cx.indent += 1;
587
588 let children: Vec<AnyElement> = parsed
589 .children
590 .iter()
591 .enumerate()
592 .map(|(ix, child)| {
593 cx.with_last_child(ix + 1 == parsed.children.len(), |cx| {
594 render_markdown_block(child, cx)
595 })
596 })
597 .collect();
598
599 cx.indent -= 1;
600
601 cx.with_common_p(div())
602 .child(
603 div()
604 .border_l_4()
605 .border_color(cx.border_color)
606 .pl_3()
607 .children(children),
608 )
609 .into_any()
610}
611
612fn render_markdown_code_block(
613 parsed: &ParsedMarkdownCodeBlock,
614 cx: &mut RenderContext,
615) -> AnyElement {
616 let body = if let Some(highlights) = parsed.highlights.as_ref() {
617 StyledText::new(parsed.contents.clone()).with_default_highlights(
618 &cx.buffer_text_style,
619 highlights.iter().filter_map(|(range, highlight_id)| {
620 highlight_id
621 .style(cx.syntax_theme.as_ref())
622 .map(|style| (range.clone(), style))
623 }),
624 )
625 } else {
626 StyledText::new(parsed.contents.clone())
627 };
628
629 let copy_block_button = IconButton::new("copy-code", IconName::Copy)
630 .icon_size(IconSize::Small)
631 .on_click({
632 let contents = parsed.contents.clone();
633 move |_, _window, cx| {
634 cx.write_to_clipboard(ClipboardItem::new_string(contents.to_string()));
635 }
636 })
637 .tooltip(Tooltip::text("Copy code block"))
638 .visible_on_hover("markdown-block");
639
640 let font = gpui::Font {
641 family: cx.buffer_font_family.clone(),
642 features: cx.buffer_text_style.font_features.clone(),
643 ..Default::default()
644 };
645
646 cx.with_common_p(div())
647 .font(font)
648 .px_3()
649 .py_3()
650 .bg(cx.code_block_background_color)
651 .rounded_sm()
652 .child(body)
653 .child(
654 div()
655 .h_flex()
656 .absolute()
657 .right_1()
658 .top_1()
659 .child(copy_block_button),
660 )
661 .into_any()
662}
663
664fn render_markdown_paragraph(parsed: &MarkdownParagraph, cx: &mut RenderContext) -> AnyElement {
665 cx.with_common_p(div())
666 .children(render_markdown_text(parsed, cx))
667 .flex()
668 .flex_col()
669 .into_any_element()
670}
671
672fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext) -> Vec<AnyElement> {
673 let mut any_element = Vec::with_capacity(parsed_new.len());
674 // these values are cloned in-order satisfy borrow checker
675 let syntax_theme = cx.syntax_theme.clone();
676 let workspace_clone = cx.workspace.clone();
677 let code_span_bg_color = cx.code_span_background_color;
678 let text_style = cx.text_style.clone();
679 let link_color = cx.link_color;
680
681 for parsed_region in parsed_new {
682 match parsed_region {
683 MarkdownParagraphChunk::Text(parsed) => {
684 let element_id = cx.next_id(&parsed.source_range);
685
686 let highlights = gpui::combine_highlights(
687 parsed.highlights.iter().filter_map(|(range, highlight)| {
688 highlight
689 .to_highlight_style(&syntax_theme)
690 .map(|style| (range.clone(), style))
691 }),
692 parsed.regions.iter().filter_map(|(range, region)| {
693 if region.code {
694 Some((
695 range.clone(),
696 HighlightStyle {
697 background_color: Some(code_span_bg_color),
698 ..Default::default()
699 },
700 ))
701 } else if region.link.is_some() {
702 Some((
703 range.clone(),
704 HighlightStyle {
705 color: Some(link_color),
706 ..Default::default()
707 },
708 ))
709 } else {
710 None
711 }
712 }),
713 );
714 let mut links = Vec::new();
715 let mut link_ranges = Vec::new();
716 for (range, region) in parsed.regions.iter() {
717 if let Some(link) = region.link.clone() {
718 links.push(link);
719 link_ranges.push(range.clone());
720 }
721 }
722 let workspace = workspace_clone.clone();
723 let element = div()
724 .child(
725 InteractiveText::new(
726 element_id,
727 StyledText::new(parsed.contents.clone())
728 .with_default_highlights(&text_style, highlights),
729 )
730 .tooltip({
731 let links = links.clone();
732 let link_ranges = link_ranges.clone();
733 move |idx, _, cx| {
734 for (ix, range) in link_ranges.iter().enumerate() {
735 if range.contains(&idx) {
736 return Some(LinkPreview::new(&links[ix].to_string(), cx));
737 }
738 }
739 None
740 }
741 })
742 .on_click(
743 link_ranges,
744 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
745 Link::Web { url } => cx.open_url(url),
746 Link::Path { path, .. } => {
747 if let Some(workspace) = &workspace {
748 _ = workspace.update(cx, |workspace, cx| {
749 workspace
750 .open_abs_path(
751 normalize_path(path.clone().as_path()),
752 OpenOptions {
753 visible: Some(OpenVisible::None),
754 ..Default::default()
755 },
756 window,
757 cx,
758 )
759 .detach();
760 });
761 }
762 }
763 },
764 ),
765 )
766 .into_any();
767 any_element.push(element);
768 }
769
770 MarkdownParagraphChunk::Image(image) => {
771 any_element.push(render_markdown_image(image, cx));
772 }
773 }
774 }
775
776 any_element
777}
778
779fn render_markdown_rule(cx: &mut RenderContext) -> AnyElement {
780 let rule = div().w_full().h(cx.scaled_rems(0.125)).bg(cx.border_color);
781 div().py(cx.scaled_rems(0.5)).child(rule).into_any()
782}
783
784fn render_markdown_image(image: &Image, cx: &mut RenderContext) -> AnyElement {
785 let image_resource = match image.link.clone() {
786 Link::Web { url } => Resource::Uri(url.into()),
787 Link::Path { path, .. } => Resource::Path(Arc::from(path)),
788 };
789
790 let element_id = cx.next_id(&image.source_range);
791 let workspace = cx.workspace.clone();
792
793 div()
794 .id(element_id)
795 .cursor_pointer()
796 .child(
797 img(ImageSource::Resource(image_resource))
798 .max_w_full()
799 .with_fallback({
800 let alt_text = image.alt_text.clone();
801 move || div().children(alt_text.clone()).into_any_element()
802 })
803 .when_some(image.height, |this, height| this.h(height))
804 .when_some(image.width, |this, width| this.w(width)),
805 )
806 .tooltip({
807 let link = image.link.clone();
808 let alt_text = image.alt_text.clone();
809 move |_, cx| {
810 InteractiveMarkdownElementTooltip::new(
811 Some(alt_text.clone().unwrap_or(link.to_string().into())),
812 "open image",
813 cx,
814 )
815 .into()
816 }
817 })
818 .on_click({
819 let link = image.link.clone();
820 move |_, window, cx| {
821 if window.modifiers().secondary() {
822 match &link {
823 Link::Web { url } => cx.open_url(url),
824 Link::Path { path, .. } => {
825 if let Some(workspace) = &workspace {
826 _ = workspace.update(cx, |workspace, cx| {
827 workspace
828 .open_abs_path(
829 path.clone(),
830 OpenOptions {
831 visible: Some(OpenVisible::None),
832 ..Default::default()
833 },
834 window,
835 cx,
836 )
837 .detach();
838 });
839 }
840 }
841 }
842 }
843 }
844 })
845 .into_any()
846}
847
848struct InteractiveMarkdownElementTooltip {
849 tooltip_text: Option<SharedString>,
850 action_text: SharedString,
851}
852
853impl InteractiveMarkdownElementTooltip {
854 pub fn new(
855 tooltip_text: Option<SharedString>,
856 action_text: impl Into<SharedString>,
857 cx: &mut App,
858 ) -> Entity<Self> {
859 let tooltip_text = tooltip_text.map(|t| util::truncate_and_trailoff(&t, 50).into());
860
861 cx.new(|_cx| Self {
862 tooltip_text,
863 action_text: action_text.into(),
864 })
865 }
866}
867
868impl Render for InteractiveMarkdownElementTooltip {
869 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
870 tooltip_container(cx, |el, _| {
871 let secondary_modifier = Keystroke {
872 modifiers: Modifiers::secondary_key(),
873 ..Default::default()
874 };
875
876 el.child(
877 v_flex()
878 .gap_1()
879 .when_some(self.tooltip_text.clone(), |this, text| {
880 this.child(Label::new(text).size(LabelSize::Small))
881 })
882 .child(
883 Label::new(format!(
884 "{}-click to {}",
885 secondary_modifier, self.action_text
886 ))
887 .size(LabelSize::Small)
888 .color(Color::Muted),
889 ),
890 )
891 })
892 }
893}
894
895/// Returns the prefix for a list item.
896fn list_item_prefix(order: usize, ordered: bool, depth: usize) -> String {
897 let ix = order.saturating_sub(1);
898 const NUMBERED_PREFIXES_1: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
899 const NUMBERED_PREFIXES_2: &str = "abcdefghijklmnopqrstuvwxyz";
900 const BULLETS: [&str; 5] = ["•", "◦", "▪", "‣", "⁃"];
901
902 if ordered {
903 match depth {
904 0 => format!("{}. ", order),
905 1 => format!(
906 "{}. ",
907 NUMBERED_PREFIXES_1
908 .chars()
909 .nth(ix % NUMBERED_PREFIXES_1.len())
910 .unwrap()
911 ),
912 _ => format!(
913 "{}. ",
914 NUMBERED_PREFIXES_2
915 .chars()
916 .nth(ix % NUMBERED_PREFIXES_2.len())
917 .unwrap()
918 ),
919 }
920 } else {
921 let depth = depth.min(BULLETS.len() - 1);
922 let bullet = BULLETS[depth];
923 return format!("{} ", bullet);
924 }
925}
926
927#[cfg(test)]
928mod tests {
929 use super::*;
930 use crate::markdown_elements::ParsedMarkdownTableColumn;
931 use crate::markdown_elements::ParsedMarkdownText;
932
933 fn text(text: &str) -> MarkdownParagraphChunk {
934 MarkdownParagraphChunk::Text(ParsedMarkdownText {
935 source_range: 0..text.len(),
936 contents: SharedString::new(text),
937 highlights: Default::default(),
938 regions: Default::default(),
939 })
940 }
941
942 fn column(
943 col_span: usize,
944 row_span: usize,
945 children: Vec<MarkdownParagraphChunk>,
946 ) -> ParsedMarkdownTableColumn {
947 ParsedMarkdownTableColumn {
948 col_span,
949 row_span,
950 is_header: false,
951 children,
952 alignment: ParsedMarkdownTableAlignment::None,
953 }
954 }
955
956 fn column_with_row_span(
957 col_span: usize,
958 row_span: usize,
959 children: Vec<MarkdownParagraphChunk>,
960 ) -> ParsedMarkdownTableColumn {
961 ParsedMarkdownTableColumn {
962 col_span,
963 row_span,
964 is_header: false,
965 children,
966 alignment: ParsedMarkdownTableAlignment::None,
967 }
968 }
969
970 #[test]
971 fn test_calculate_table_columns_count() {
972 assert_eq!(0, calculate_table_columns_count(&vec![]));
973
974 assert_eq!(
975 1,
976 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
977 column(1, 1, vec![text("column1")])
978 ])])
979 );
980
981 assert_eq!(
982 2,
983 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
984 column(1, 1, vec![text("column1")]),
985 column(1, 1, vec![text("column2")]),
986 ])])
987 );
988
989 assert_eq!(
990 2,
991 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
992 column(2, 1, vec![text("column1")])
993 ])])
994 );
995
996 assert_eq!(
997 3,
998 calculate_table_columns_count(&vec![ParsedMarkdownTableRow::with_columns(vec![
999 column(1, 1, vec![text("column1")]),
1000 column(2, 1, vec![text("column2")]),
1001 ])])
1002 );
1003
1004 assert_eq!(
1005 2,
1006 calculate_table_columns_count(&vec![
1007 ParsedMarkdownTableRow::with_columns(vec![
1008 column(1, 1, vec![text("column1")]),
1009 column(1, 1, vec![text("column2")]),
1010 ]),
1011 ParsedMarkdownTableRow::with_columns(vec![column(1, 1, vec![text("column1")]),])
1012 ])
1013 );
1014
1015 assert_eq!(
1016 3,
1017 calculate_table_columns_count(&vec![
1018 ParsedMarkdownTableRow::with_columns(vec![
1019 column(1, 1, vec![text("column1")]),
1020 column(1, 1, vec![text("column2")]),
1021 ]),
1022 ParsedMarkdownTableRow::with_columns(vec![column(3, 3, vec![text("column1")]),])
1023 ])
1024 );
1025 }
1026
1027 #[test]
1028 fn test_row_span_support() {
1029 assert_eq!(
1030 3,
1031 calculate_table_columns_count(&vec![
1032 ParsedMarkdownTableRow::with_columns(vec![
1033 column_with_row_span(1, 2, vec![text("spans 2 rows")]),
1034 column(1, 1, vec![text("column2")]),
1035 column(1, 1, vec![text("column3")]),
1036 ]),
1037 ParsedMarkdownTableRow::with_columns(vec![
1038 // First column is covered by row span from above
1039 column(1, 1, vec![text("column2 row2")]),
1040 column(1, 1, vec![text("column3 row2")]),
1041 ])
1042 ])
1043 );
1044
1045 assert_eq!(
1046 4,
1047 calculate_table_columns_count(&vec![
1048 ParsedMarkdownTableRow::with_columns(vec![
1049 column_with_row_span(1, 3, vec![text("spans 3 rows")]),
1050 column_with_row_span(2, 1, vec![text("spans 2 cols")]),
1051 column(1, 1, vec![text("column4")]),
1052 ]),
1053 ParsedMarkdownTableRow::with_columns(vec![
1054 // First column covered by row span
1055 column(1, 1, vec![text("column2")]),
1056 column(1, 1, vec![text("column3")]),
1057 column(1, 1, vec![text("column4")]),
1058 ]),
1059 ParsedMarkdownTableRow::with_columns(vec![
1060 // First column still covered by row span
1061 column(3, 1, vec![text("spans 3 cols")]),
1062 ])
1063 ])
1064 );
1065 }
1066
1067 #[test]
1068 fn test_list_item_prefix() {
1069 assert_eq!(list_item_prefix(1, true, 0), "1. ");
1070 assert_eq!(list_item_prefix(2, true, 0), "2. ");
1071 assert_eq!(list_item_prefix(3, true, 0), "3. ");
1072 assert_eq!(list_item_prefix(11, true, 0), "11. ");
1073 assert_eq!(list_item_prefix(1, true, 1), "A. ");
1074 assert_eq!(list_item_prefix(2, true, 1), "B. ");
1075 assert_eq!(list_item_prefix(3, true, 1), "C. ");
1076 assert_eq!(list_item_prefix(1, true, 2), "a. ");
1077 assert_eq!(list_item_prefix(2, true, 2), "b. ");
1078 assert_eq!(list_item_prefix(7, true, 2), "g. ");
1079 assert_eq!(list_item_prefix(1, true, 1), "A. ");
1080 assert_eq!(list_item_prefix(1, true, 2), "a. ");
1081 assert_eq!(list_item_prefix(1, false, 0), "• ");
1082 assert_eq!(list_item_prefix(1, false, 1), "◦ ");
1083 assert_eq!(list_item_prefix(1, false, 2), "▪ ");
1084 assert_eq!(list_item_prefix(1, false, 3), "‣ ");
1085 assert_eq!(list_item_prefix(1, false, 4), "⁃ ");
1086 }
1087}