1use std::sync::Arc;
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
5 AnyElement, App, Bounds, ClickEvent, ContentMask, Element, ElementId, Entity, GlobalElementId,
6 Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
7 MouseButton, ParentElement, Pixels, Refineable as _, SharedString, StyleRefinement, Styled,
8 Window, div, point, px,
9};
10
11use crate::StyledExt;
12use crate::scroll::ScrollableElement;
13use crate::text::TextViewFormat;
14use crate::text::markdown_ext::{MarkdownExtensions, MarkdownNode, MarkdownPlugin};
15use crate::text::node::{CodeBlock, TableData};
16use crate::text::state::{LineSpan, SelectionFormat, TextViewState};
17use crate::{global_state::UiGlobalState, text::TextViewStyle};
18
19pub(crate) type CodeBlockActionsFn =
21 dyn Fn(&CodeBlock, &mut Window, &mut App) -> AnyElement + Send + Sync;
22
23pub(crate) type TableActionsFn =
25 dyn Fn(&TableData, &mut Window, &mut App) -> AnyElement + Send + Sync;
26
27pub(crate) type LinkClickHandlerFn =
28 dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
29
30pub(crate) fn handle_link_click(
31 handler: &Option<Arc<LinkClickHandlerFn>>,
32 url: SharedString,
33 event: ClickEvent,
34 window: &mut Window,
35 cx: &mut App,
36) {
37 if let Some(handler) = handler {
38 handler(&url, &event, window, cx);
39 } else if match &event {
40 ClickEvent::Mouse(click) => {
41 matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
42 }
43 ClickEvent::Keyboard(_) => true,
44 ClickEvent::Touch(click) => !click.long_press,
45 } {
46 cx.open_url(&url);
47 }
48}
49
50#[derive(Clone)]
67pub struct TextView {
68 id: ElementId,
69 format: Option<TextViewFormat>,
70 text: Option<SharedString>,
71 pub(crate) state: Option<Entity<TextViewState>>,
72 text_view_style: TextViewStyle,
73 style: StyleRefinement,
74 selectable: bool,
75 selection_format: SelectionFormat,
76 scrollable: bool,
77 max_lines: Option<usize>,
78 code_block_actions: Option<Arc<CodeBlockActionsFn>>,
79 table_actions: Option<Arc<TableActionsFn>>,
80 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
81 markdown_extensions: Arc<MarkdownExtensions>,
82}
83
84pub trait TextViewPlugin {
86 fn setup(self, text_view: TextView) -> TextView;
87}
88
89impl<P> TextViewPlugin for P
90where
91 P: MarkdownPlugin,
92{
93 fn setup(self, mut text_view: TextView) -> TextView {
94 let extensions = Arc::make_mut(&mut text_view.markdown_extensions);
95 let current = std::mem::take(extensions);
96 *extensions = current.plugin(self);
97 text_view
98 }
99}
100
101impl Styled for TextView {
102 fn style(&mut self) -> &mut StyleRefinement {
103 &mut self.style
104 }
105}
106
107impl TextView {
108 pub fn new(state: &Entity<TextViewState>) -> Self {
110 Self {
111 id: ElementId::Name(state.entity_id().to_string().into()),
112 state: Some(state.clone()),
113 format: None,
114 text: None,
115 text_view_style: TextViewStyle::default(),
116 style: StyleRefinement::default(),
117 selectable: false,
118 selection_format: SelectionFormat::default(),
119 scrollable: false,
120 max_lines: None,
121 code_block_actions: None,
122 table_actions: None,
123 link_click_handler: None,
124 markdown_extensions: Arc::default(),
125 }
126 }
127
128 pub fn markdown(id: impl Into<ElementId>, markdown: impl Into<SharedString>) -> Self {
130 Self {
131 id: id.into(),
132 format: Some(TextViewFormat::Markdown),
133 text: Some(markdown.into()),
134 text_view_style: TextViewStyle::default(),
135 style: StyleRefinement::default(),
136 state: None,
137 selectable: false,
138 selection_format: SelectionFormat::default(),
139 scrollable: false,
140 max_lines: None,
141 code_block_actions: None,
142 table_actions: None,
143 link_click_handler: None,
144 markdown_extensions: Arc::default(),
145 }
146 }
147
148 pub fn html(id: impl Into<ElementId>, html: impl Into<SharedString>) -> Self {
150 Self {
151 id: id.into(),
152 format: Some(TextViewFormat::Html),
153 text: Some(html.into()),
154 text_view_style: TextViewStyle::default(),
155 style: StyleRefinement::default(),
156 state: None,
157 selectable: false,
158 selection_format: SelectionFormat::default(),
159 scrollable: false,
160 max_lines: None,
161 code_block_actions: None,
162 table_actions: None,
163 link_click_handler: None,
164 markdown_extensions: Arc::default(),
165 }
166 }
167
168 pub fn style(mut self, style: TextViewStyle) -> Self {
170 self.text_view_style = style;
171 self
172 }
173
174 pub fn selectable(mut self, selectable: bool) -> Self {
176 self.selectable = selectable;
177 self
178 }
179
180 pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
185 self.selection_format = selection_format;
186 self
187 }
188
189 pub fn scrollable(mut self, scrollable: bool) -> Self {
202 self.scrollable = scrollable;
203 self
204 }
205
206 pub fn max_lines(mut self, max_lines: usize) -> Self {
225 self.max_lines = Some(max_lines);
226 self
227 }
228
229 pub fn code_block_actions<F, E>(mut self, f: F) -> Self
234 where
235 F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
236 E: IntoElement,
237 {
238 self.code_block_actions = Some(Arc::new(move |code_block, window, cx| {
239 f(&code_block, window, cx).into_any_element()
240 }));
241 self
242 }
243
244 pub fn table_actions<F, E>(mut self, f: F) -> Self
249 where
250 F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
251 E: IntoElement,
252 {
253 self.table_actions = Some(Arc::new(move |table, window, cx| {
254 f(table, window, cx).into_any_element()
255 }));
256 self
257 }
258
259 pub fn on_link_click<F>(mut self, handler: F) -> Self
264 where
265 F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
266 {
267 self.link_click_handler = Some(Arc::new(handler));
268 self
269 }
270
271 pub fn markdown_extensions(mut self, extensions: MarkdownExtensions) -> Self {
273 self.markdown_extensions = Arc::new(extensions);
274 self
275 }
276
277 pub fn markdown_mdx(mut self) -> Self {
282 let extensions = Arc::make_mut(&mut self.markdown_extensions);
283 *extensions = extensions.clone().mdx();
284 self
285 }
286
287 pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
293 where
294 F: for<'a> Fn(
295 &markdown::mdast::Node,
296 &crate::text::MarkdownParseContext<'a>,
297 ) -> Option<MarkdownNode>
298 + Send
299 + Sync
300 + 'static,
301 {
302 Arc::make_mut(&mut self.markdown_extensions).push_block_parser(parser);
303 self
304 }
305
306 pub fn markdown_block_renderer<F, E>(
308 mut self,
309 name: impl Into<SharedString>,
310 renderer: F,
311 ) -> Self
312 where
313 F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
314 E: IntoElement,
315 {
316 Arc::make_mut(&mut self.markdown_extensions).push_block_renderer(name, renderer);
317 self
318 }
319
320 pub fn plugin<P>(self, plugin: P) -> Self
322 where
323 P: TextViewPlugin,
324 {
325 plugin.setup(self)
326 }
327}
328
329impl IntoElement for TextView {
330 type Element = Self;
331
332 fn into_element(self) -> Self::Element {
333 self
334 }
335}
336
337pub struct TextViewLayoutState {
338 state: Entity<TextViewState>,
339 element: AnyElement,
340}
341
342pub struct TextViewPrepaintState {
343 hitbox: Hitbox,
344 clip_bottom: Option<Pixels>,
348}
349
350const CLIP_EPSILON: Pixels = px(1.);
353
354fn last_line_bottom_above(spans: &[LineSpan], y: Pixels) -> Option<(Pixels, Pixels)> {
357 let mut last: Option<(Pixels, Pixels)> = None;
358 let mut keep = |bottom: Pixels, line_height: Pixels| {
359 if bottom <= y + CLIP_EPSILON && last.is_none_or(|(last, _)| bottom > last) {
360 last = Some((bottom, line_height));
361 }
362 };
363
364 for span in spans {
365 if span.line_height <= px(0.) {
366 continue;
367 }
368 let mut bottom = span.top + span.line_height;
369 while bottom <= span.bottom + CLIP_EPSILON {
370 keep(bottom, span.line_height);
371 bottom += span.line_height;
372 }
373 keep(span.bottom, span.line_height);
375 }
376
377 last
378}
379
380fn line_safe_clip_bottom(
390 spans: &[LineSpan],
391 box_bottom: Pixels,
392 content_bottom: Pixels,
393) -> Option<Pixels> {
394 let mut clip = box_bottom;
395
396 for span in spans {
397 if span.line_height <= px(0.)
398 || span.top >= box_bottom
399 || span.bottom <= box_bottom + CLIP_EPSILON
400 {
401 continue;
402 }
403 let whole_lines = ((box_bottom - span.top) / span.line_height).floor();
404 let line_top = span.top + span.line_height * whole_lines;
405 if line_top < box_bottom - CLIP_EPSILON {
407 clip = clip.min(line_top);
408 }
409 }
410
411 let Some((last_line_bottom, line_height)) = last_line_bottom_above(spans, clip) else {
412 return None;
417 };
418
419 if content_bottom > box_bottom + CLIP_EPSILON {
423 let strip = clip - last_line_bottom;
424 if strip > CLIP_EPSILON && strip < line_height {
425 clip = last_line_bottom;
426 }
427 }
428
429 (clip < box_bottom - CLIP_EPSILON).then_some(clip)
430}
431
432impl Element for TextView {
433 type RequestLayoutState = TextViewLayoutState;
434 type PrepaintState = TextViewPrepaintState;
435
436 fn id(&self) -> Option<ElementId> {
437 Some(self.id.clone())
438 }
439
440 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
441 None
442 }
443
444 fn request_layout(
445 &mut self,
446 _: Option<&GlobalElementId>,
447 _: Option<&InspectorElementId>,
448 window: &mut Window,
449 cx: &mut App,
450 ) -> (LayoutId, Self::RequestLayoutState) {
451 let state = if let Some(state) = self.state.clone() {
452 state
453 } else {
454 let default_format = self.format.unwrap_or(TextViewFormat::Markdown);
455 let default_text = self.text.clone().unwrap_or_default();
456
457 let state = window.use_keyed_state(
458 SharedString::from(format!("{}/state", self.id)),
459 cx,
460 move |_, cx| {
461 if default_format == TextViewFormat::Markdown {
462 TextViewState::markdown(default_text.as_str(), cx)
463 } else {
464 TextViewState::html(default_text.as_str(), cx)
465 }
466 },
467 );
468 self.state = Some(state.clone());
469 state
470 };
471
472 let max_lines = self.max_lines.filter(|_| !self.scrollable);
475
476 state.update(cx, |state, cx| {
477 state.code_block_actions = self.code_block_actions.clone();
478 state.table_actions = self.table_actions.clone();
479 state.link_click_handler = self.link_click_handler.clone();
480 state.set_markdown_extensions(self.markdown_extensions.clone(), cx);
481 state.selectable = self.selectable;
482 state.selection_format = self.selection_format;
483 state.scrollable = self.scrollable;
484 state.max_lines = max_lines;
485 if state.text_view_style != self.text_view_style {
486 state.selection_revision = state.selection_revision.wrapping_add(1);
487 }
488 state.text_view_style = self.text_view_style.clone();
489
490 if let Some(text) = self.text.clone() {
491 state.set_text(text.as_str(), cx);
492 }
493 });
494
495 let focus_handle = state.read(cx).focus_handle.clone();
496 let list_state = state.read(cx).list_state.clone();
497
498 let max_lines_cap = max_lines.map(|max_lines| {
502 let mut text_style = window.text_style();
503 text_style.refine(&self.style.text);
504 text_style.line_height_in_pixels(window.rem_size()) * max_lines as f32
505 });
506
507 let mut el = div()
508 .key_context("TextView")
509 .track_focus(&focus_handle)
510 .when(self.scrollable, |this| {
511 this.size_full().vertical_scrollbar(&list_state)
512 })
513 .when_some(max_lines_cap, |this, cap| this.max_h(cap).overflow_hidden())
514 .relative()
515 .on_action(move |_: &crate::input::Copy, window, cx| {
516 let text = gpui_base::TextSelection::selected_text(window, cx)
517 .trim()
518 .to_string();
519 if text.is_empty() {
520 cx.propagate();
521 return;
522 }
523 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
524 })
525 .on_action(window.listener_for(&state, TextViewState::on_action_select_all))
526 .child(state.clone())
527 .refine_style(&self.style)
528 .into_any_element();
529 let layout_id = el.request_layout(window, cx);
530 (layout_id, TextViewLayoutState { state, element: el })
531 }
532
533 fn prepaint(
534 &mut self,
535 _: Option<&GlobalElementId>,
536 _: Option<&InspectorElementId>,
537 bounds: Bounds<Pixels>,
538 request_layout: &mut Self::RequestLayoutState,
539 window: &mut Window,
540 cx: &mut App,
541 ) -> Self::PrepaintState {
542 let state = request_layout.state.clone();
543 let max_lines_active = state.read(cx).max_lines.is_some();
544 if max_lines_active {
545 if let Ok(mut line_spans) = state.read(cx).line_spans.lock() {
546 line_spans.clear();
547 }
548 UiGlobalState::global_mut(cx)
551 .text_view_state_stack
552 .push(state.clone());
553 }
554 request_layout.element.prepaint(window, cx);
555 if max_lines_active {
556 UiGlobalState::global_mut(cx).text_view_state_stack.pop();
557 }
558
559 let mut clip_bottom = None;
560 if max_lines_active {
561 let (line_spans, content_bottom) = {
562 let state = state.read(cx);
563 (
564 state
565 .line_spans
566 .lock()
567 .map(|spans| spans.clone())
568 .unwrap_or_default(),
569 state.bounds().bottom(),
570 )
571 };
572 let clipped = content_bottom > bounds.bottom() + px(1.);
576 if state.read(cx).clamped != clipped {
579 state.update(cx, |state, cx| {
580 state.clamped = clipped;
581 cx.notify();
582 });
583 }
584 if clipped {
585 clip_bottom = line_safe_clip_bottom(&line_spans, bounds.bottom(), content_bottom);
586 }
587 }
588
589 TextViewPrepaintState {
590 hitbox: window.insert_hitbox(bounds, HitboxBehavior::Normal),
591 clip_bottom,
592 }
593 }
594
595 fn paint(
596 &mut self,
597 _: Option<&GlobalElementId>,
598 _: Option<&InspectorElementId>,
599 bounds: Bounds<Pixels>,
600 request_layout: &mut Self::RequestLayoutState,
601 prepaint: &mut Self::PrepaintState,
602 window: &mut Window,
603 cx: &mut App,
604 ) {
605 let state = &request_layout.state;
606 if self.selectable {
607 state.update(cx, |state, _| state.selection_adapter.begin_frame());
608 }
609
610 UiGlobalState::global_mut(cx)
611 .text_view_state_stack
612 .push(state.clone());
613 if let Some(clip_bottom) = prepaint.clip_bottom {
614 let mask = ContentMask {
617 bounds: Bounds::from_corners(bounds.origin, point(bounds.right(), clip_bottom)),
618 };
619 window.with_content_mask(Some(mask), |window| {
620 request_layout.element.paint(window, cx);
621 });
622 } else {
623 request_layout.element.paint(window, cx);
624 }
625 UiGlobalState::global_mut(cx).text_view_state_stack.pop();
626
627 if self.selectable {
628 let (adapter, scroll_offset, content_bounds) = {
629 let state = state.read(cx);
630 (
631 state.selection_adapter.clone(),
632 state.scroll_offset(),
633 state.bounds(),
634 )
635 };
636 let document_order = UiGlobalState::global_mut(cx).next_selection_document_order();
637 adapter.register(
638 prepaint.hitbox.clone(),
639 content_bounds,
640 scroll_offset,
641 document_order,
642 window,
643 cx,
644 );
645 }
646 }
647}
648
649#[cfg(test)]
650mod tests {
651 use super::{TextView, TextViewPlugin};
652 use crate::text::{TableData, TextViewState, TextViewStyle};
653 use gpui::{
654 AppContext as _, Bounds, ClickEvent, Context, Entity, InteractiveElement as _, IntoElement,
655 Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Overflow, ParentElement as _, Pixels,
656 Render, SharedString, StyleRefinement, Styled as _, TestAppContext, VisualTestContext,
657 Window, div, point, px,
658 };
659
660 struct TextViewTestRoot {
661 text_view: Entity<TextViewState>,
662 }
663
664 struct DummyTextViewPlugin;
665
666 impl TextViewPlugin for DummyTextViewPlugin {
667 fn setup(self, mut text_view: TextView) -> TextView {
668 text_view.selectable = true;
669 text_view
670 }
671 }
672
673 impl TextViewTestRoot {
674 fn new(text: &str, cx: &mut Context<Self>) -> Self {
675 let text = text.to_string();
676 let text_view = cx.new(|cx| TextViewState::markdown(&text, cx));
677 Self { text_view }
678 }
679 }
680
681 impl Render for TextViewTestRoot {
682 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
683 div()
684 .w(px(160.))
685 .child(
686 div()
687 .h(px(24.))
688 .overflow_hidden()
689 .child(TextView::new(&self.text_view).selectable(true)),
690 )
691 .child(div().h(px(40.)).child("footer"))
692 }
693 }
694
695 struct InlineImageTextViewTestRoot {
696 text_view: Entity<TextViewState>,
697 }
698
699 impl InlineImageTextViewTestRoot {
700 fn new(cx: &mut Context<Self>) -> Self {
701 let text_view = cx.new(|cx| {
702 TextViewState::markdown(
703 "Build Status  after",
704 cx,
705 )
706 });
707 Self { text_view }
708 }
709 }
710
711 impl Render for InlineImageTextViewTestRoot {
712 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
713 div()
714 .w(px(420.))
715 .child(TextView::new(&self.text_view).selectable(true))
716 }
717 }
718
719 #[gpui::test]
720 fn inline_image_keeps_surrounding_text_on_same_line(cx: &mut TestAppContext) {
721 cx.update(crate::init);
722 let (root, cx) = cx.add_window_view(|window, cx| {
723 let content = cx.new(|cx| InlineImageTextViewTestRoot::new(cx));
724 crate::Root::new(content, window, cx)
725 });
726 let content = root.read_with(cx, |root, _| {
727 root.view()
728 .clone()
729 .downcast::<InlineImageTextViewTestRoot>()
730 .unwrap()
731 });
732 let cx: &mut VisualTestContext = cx;
733
734 cx.run_until_parked();
735 cx.update(|window, cx| {
736 let _ = window.draw(cx);
737 });
738
739 let inline_bounds = content.read_with(cx, |content, cx| {
740 content.text_view.read(cx).selection_adapter.text_bounds()
741 });
742
743 assert_eq!(inline_bounds.len(), 2);
744 assert_eq!(
745 inline_bounds[0].top(),
746 inline_bounds[1].top(),
747 "text before and after an inline image should share a rendered line"
748 );
749 assert!(
750 inline_bounds[1].left() - inline_bounds[0].right() > px(8.),
751 "inline image should reserve horizontal space in the text layout"
752 );
753 assert!(
754 inline_bounds[1].left() - inline_bounds[0].right() < px(40.),
755 "unloaded inline image fallback should stay generic and compact"
756 );
757 }
758
759 #[gpui::test]
760 fn inline_html_image_after_newline_does_not_panic(cx: &mut TestAppContext) {
761 cx.update(crate::init);
762 let (_, cx) = cx.add_window_view(|_, cx| {
763 TextViewTestRoot::new(
764 "Hi\n[<img src=\"https://example.com/image.svg\">](https://google.com/)",
765 cx,
766 )
767 });
768 let cx: &mut VisualTestContext = cx;
769
770 cx.run_until_parked();
771 cx.update(|window, cx| {
772 let _ = window.draw(cx);
773 });
774 }
775
776 #[gpui::test]
777 fn list_item_renders_fenced_code_block_at_document_width(cx: &mut TestAppContext) {
778 struct ListItemBlockRoot;
779
780 impl Render for ListItemBlockRoot {
781 fn render(
782 &mut self,
783 _window: &mut Window,
784 _cx: &mut Context<Self>,
785 ) -> impl IntoElement {
786 div().w(px(840.)).h(px(400.)).child(
787 crate::h_resizable("markdown-width-test")
788 .child(crate::resizable_panel().child(div()))
789 .child(crate::resizable_panel().child(
790 TextView::markdown(
791 "list-with-code",
792 "1. List item\n ```rust\n nested code\n ```\n\n```rust\ntop-level code\n```",
793 )
794 .code_block_actions(|code_block, _, _| {
795 let selector = if code_block.code().contains("nested") {
796 "nested-code-action"
797 } else {
798 "top-level-code-action"
799 };
800 div()
801 .debug_selector(move || selector.into())
802 .child("Copy")
803 })
804 .scrollable(true)
805 .p_5()
806 .flex_none(),
807 )),
808 )
809 }
810 }
811
812 cx.update(crate::init);
813 let (_, cx) = cx.add_window_view(|_, _| ListItemBlockRoot);
814 let cx: &mut VisualTestContext = cx;
815
816 cx.run_until_parked();
817 cx.update(|window, cx| {
818 let _ = window.draw(cx);
819 });
820
821 let nested_action = cx.debug_bounds("nested-code-action").unwrap();
822 let top_level_action = cx.debug_bounds("top-level-code-action").unwrap();
823 assert!(
824 top_level_action.right() - nested_action.right() < px(32.),
825 "nested code block should fill the list item's available width"
826 );
827 }
828
829 fn draw_table_with_actions(
833 cx: &mut TestAppContext,
834 scroll: bool,
835 ) -> (Bounds<Pixels>, TableData) {
836 use std::sync::{Arc, Mutex};
837
838 struct TableRoot {
839 scroll: bool,
840 captured: Arc<Mutex<Vec<TableData>>>,
841 }
842
843 impl Render for TableRoot {
844 fn render(
845 &mut self,
846 _window: &mut Window,
847 _cx: &mut Context<Self>,
848 ) -> impl IntoElement {
849 let captured = self.captured.clone();
850 let mut table_style = StyleRefinement::default();
851 if self.scroll {
852 table_style.overflow.x = Some(Overflow::Scroll);
853 }
854
855 div().w(px(320.)).child(
856 TextView::markdown(
857 "table-actions",
858 "| Name | Age |\n|:--|--:|\n| Alice | 30 |\n| Bob | 41 |",
859 )
860 .style(TextViewStyle::default().table(table_style))
861 .table_actions(move |table, _, _| {
862 if let Ok(mut captured) = captured.lock() {
863 captured.push(table.clone());
864 }
865 div().debug_selector(|| "table-action".into()).child("Copy")
866 }),
867 )
868 }
869 }
870
871 cx.update(crate::init);
872 let captured = Arc::new(Mutex::new(Vec::new()));
873 let (_, cx) = cx.add_window_view({
874 let captured = captured.clone();
875 move |_, _| TableRoot { scroll, captured }
876 });
877 let cx: &mut VisualTestContext = cx;
878
879 cx.run_until_parked();
880 cx.update(|window, cx| {
881 let _ = window.draw(cx);
882 });
883
884 let bounds = cx
885 .debug_bounds("table-action")
886 .expect("table actions should be painted");
887 let data = captured
888 .lock()
889 .expect("captured table data")
890 .last()
891 .cloned()
892 .expect("table actions hook should receive the table");
893
894 (bounds, data)
895 }
896
897 #[gpui::test]
898 fn table_actions_render_below_the_table(cx: &mut TestAppContext) {
899 for scroll in [false, true] {
900 let (bounds, data) = draw_table_with_actions(cx, scroll);
901
902 assert!(
904 bounds.top() > px(40.),
905 "actions should sit below the table (scroll: {scroll}), got {:?}",
906 bounds.top()
907 );
908 assert_eq!(data.headers, vec!["Name", "Age"]);
909 assert_eq!(data.rows, vec![vec!["Alice", "30"], vec!["Bob", "41"]]);
910 assert_eq!(
911 data.markdown,
912 "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n| Bob | 41 |"
913 );
914 assert_eq!(data.span, Some(0..52));
915 }
916 }
917
918 #[test]
919 fn plugin_accepts_text_view_plugins_beyond_markdown() {
920 let view = TextView::markdown("plugin-test", "").plugin(DummyTextViewPlugin);
921
922 assert!(view.selectable);
923 }
924
925 #[gpui::test]
926 fn clipped_markdown_link_does_not_open(cx: &mut TestAppContext) {
927 cx.update(crate::init);
928 let (_, cx) = cx.add_window_view(|_, cx| {
929 TextViewTestRoot::new("visible\n\n[hidden](https://example.com)", cx)
930 });
931 let cx: &mut VisualTestContext = cx;
932
933 cx.simulate_click(point(px(10.), px(34.)), Modifiers::default());
934
935 assert_eq!(cx.opened_url(), None);
936 }
937
938 struct MaxLinesTestRoot {
939 text_view: Entity<TextViewState>,
940 max_lines: usize,
941 }
942
943 impl MaxLinesTestRoot {
944 fn new(text: &str, max_lines: usize, cx: &mut Context<Self>) -> Self {
945 let text_view = cx.new(|cx| TextViewState::markdown(text, cx));
946 Self {
947 text_view,
948 max_lines,
949 }
950 }
951 }
952
953 impl Render for MaxLinesTestRoot {
954 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
955 div()
956 .w(px(200.))
957 .child(TextView::new(&self.text_view).max_lines(self.max_lines))
958 }
959 }
960
961 #[test]
962 fn the_clip_only_moves_for_a_straddling_glyph_line() {
963 use super::line_safe_clip_bottom;
964 use crate::text::state::LineSpan;
965
966 let spans = [
967 LineSpan {
969 top: px(0.),
970 bottom: px(60.),
971 line_height: px(20.),
972 },
973 LineSpan {
975 top: px(68.),
976 bottom: px(128.),
977 line_height: px(20.),
978 },
979 ];
980
981 let below = px(400.);
983
984 assert_eq!(
986 line_safe_clip_bottom(&spans, px(100.), below),
987 Some(px(88.))
988 );
989
990 assert_eq!(line_safe_clip_bottom(&spans, px(88.), below), None);
992
993 assert_eq!(line_safe_clip_bottom(&spans, px(64.), below), Some(px(60.)));
996
997 let one_block = [LineSpan {
1000 top: px(0.),
1001 bottom: px(60.),
1002 line_height: px(20.),
1003 }];
1004 assert_eq!(line_safe_clip_bottom(&one_block, px(200.), below), None);
1005
1006 assert_eq!(line_safe_clip_bottom(&spans, px(130.), px(128.)), None);
1009 }
1010
1011 #[test]
1012 fn a_line_taller_than_the_budget_keeps_the_part_that_fits() {
1013 use super::line_safe_clip_bottom;
1014 use crate::text::state::LineSpan;
1015
1016 let heading = [LineSpan {
1018 top: px(70.),
1019 bottom: px(98.),
1020 line_height: px(28.),
1021 }];
1022
1023 assert_eq!(line_safe_clip_bottom(&heading, px(96.), px(400.)), None);
1024 }
1025
1026 #[test]
1027 fn the_clip_does_not_stop_on_a_row_of_border_and_padding() {
1028 use super::line_safe_clip_bottom;
1029 use crate::text::state::LineSpan;
1030
1031 let rows = [
1034 LineSpan {
1035 top: px(100.),
1036 bottom: px(126.),
1037 line_height: px(26.),
1038 },
1039 LineSpan {
1040 top: px(135.),
1041 bottom: px(161.),
1042 line_height: px(26.),
1043 },
1044 ];
1045
1046 assert_eq!(
1049 line_safe_clip_bottom(&rows, px(148.), px(400.)),
1050 Some(px(126.))
1051 );
1052 }
1053
1054 struct ClampedPageRoot {
1060 text_view: Entity<TextViewState>,
1061 max_lines: usize,
1062 }
1063
1064 impl Render for ClampedPageRoot {
1065 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1066 use crate::scroll::ScrollableElement as _;
1067 use crate::{h_flex, v_flex};
1068
1069 v_flex()
1070 .size_full()
1071 .p_4()
1072 .gap_4()
1073 .child(h_flex().max_w(px(480.)).gap_3().child("header"))
1074 .child(
1075 v_flex()
1076 .flex_1()
1077 .min_h_0()
1078 .gap_4()
1079 .child(
1080 v_flex()
1081 .max_w(px(480.))
1082 .p_3()
1083 .gap_2()
1084 .child(TextView::new(&self.text_view).max_lines(self.max_lines)),
1085 )
1086 .overflow_y_scrollbar(),
1087 )
1088 }
1089 }
1090
1091 #[gpui::test]
1092 fn max_lines_measures_overflow_inside_a_sized_page(cx: &mut TestAppContext) {
1093 cx.update(crate::init);
1094 let (root, cx) = cx.add_window_view(|_, cx| {
1095 let text_view = cx.new(|cx| {
1096 TextViewState::markdown(
1097 "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth\n\nseventh",
1098 cx,
1099 )
1100 });
1101 ClampedPageRoot {
1102 text_view,
1103 max_lines: 3,
1104 }
1105 });
1106 let cx: &mut VisualTestContext = cx;
1107
1108 assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
1109 }
1110
1111 #[gpui::test]
1112 fn max_lines_clamps_overflowing_content(cx: &mut TestAppContext) {
1113 cx.update(crate::init);
1114 let (root, cx) = cx.add_window_view(|_, cx| {
1115 MaxLinesTestRoot::new(
1116 "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth",
1117 2,
1118 cx,
1119 )
1120 });
1121 let cx: &mut VisualTestContext = cx;
1122
1123 assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
1124 }
1125
1126 #[gpui::test]
1127 fn max_lines_leaves_short_content_unclamped(cx: &mut TestAppContext) {
1128 cx.update(crate::init);
1129 let (root, cx) = cx.add_window_view(|_, cx| MaxLinesTestRoot::new("only line", 3, cx));
1130 let cx: &mut VisualTestContext = cx;
1131
1132 assert!(!root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
1133 }
1134
1135 #[gpui::test]
1136 fn max_lines_disables_links_hidden_by_the_clamp(cx: &mut TestAppContext) {
1137 cx.update(crate::init);
1138 let (_, cx) = cx.add_window_view(|_, cx| {
1139 MaxLinesTestRoot::new(
1140 "first\n\nsecond\n\nthird\n\n[hidden](https://example.com)",
1141 2,
1142 cx,
1143 )
1144 });
1145 let cx: &mut VisualTestContext = cx;
1146
1147 cx.simulate_click(point(px(10.), px(150.)), Modifiers::default());
1149
1150 assert_eq!(cx.opened_url(), None);
1151 }
1152
1153 #[gpui::test]
1154 fn markdown_link_opens_url_without_handler(cx: &mut TestAppContext) {
1155 cx.update(crate::init);
1156 let (_, cx) =
1157 cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
1158 let cx: &mut VisualTestContext = cx;
1159
1160 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1161
1162 assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
1163 }
1164
1165 #[gpui::test]
1166 fn right_click_does_not_open_url_without_handler(cx: &mut TestAppContext) {
1167 cx.update(crate::init);
1168 let (_, cx) =
1169 cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
1170 let cx: &mut VisualTestContext = cx;
1171
1172 cx.simulate_mouse_down(
1173 point(px(10.), px(10.)),
1174 MouseButton::Right,
1175 Modifiers::default(),
1176 );
1177 cx.simulate_mouse_up(
1178 point(px(10.), px(10.)),
1179 MouseButton::Right,
1180 Modifiers::default(),
1181 );
1182
1183 assert_eq!(cx.opened_url(), None);
1184 }
1185
1186 #[gpui::test]
1187 fn link_handler_receives_button_and_modifiers(cx: &mut TestAppContext) {
1188 use std::sync::{Arc, Mutex};
1189
1190 struct LinkRoot {
1191 text_view: Entity<TextViewState>,
1192 clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
1193 }
1194
1195 impl Render for LinkRoot {
1196 fn render(
1197 &mut self,
1198 _window: &mut Window,
1199 _cx: &mut Context<Self>,
1200 ) -> impl IntoElement {
1201 let clicks = self.clicks.clone();
1202 div()
1203 .w(px(240.))
1204 .child(
1205 TextView::new(&self.text_view).on_link_click(move |url, event, _, _| {
1206 clicks.lock().unwrap().push((url.clone(), event.clone()));
1207 }),
1208 )
1209 }
1210 }
1211
1212 cx.update(crate::init);
1213 let clicks = Arc::new(Mutex::new(Vec::new()));
1214 let captured = clicks.clone();
1215 let (_, cx) = cx.add_window_view(move |_, cx| LinkRoot {
1216 text_view: cx.new(|cx| TextViewState::markdown("[example](https://example.com)", cx)),
1217 clicks,
1218 });
1219 let cx: &mut VisualTestContext = cx;
1220
1221 let mut modifiers = Modifiers::default();
1222 modifiers.control = true;
1223 cx.simulate_click(point(px(10.), px(10.)), modifiers);
1224 cx.simulate_mouse_down(
1225 point(px(10.), px(10.)),
1226 MouseButton::Middle,
1227 Modifiers::default(),
1228 );
1229 cx.simulate_mouse_up(
1230 point(px(10.), px(10.)),
1231 MouseButton::Middle,
1232 Modifiers::default(),
1233 );
1234 cx.simulate_mouse_down(
1235 point(px(10.), px(10.)),
1236 MouseButton::Right,
1237 Modifiers::default(),
1238 );
1239 cx.simulate_mouse_up(
1240 point(px(10.), px(10.)),
1241 MouseButton::Right,
1242 Modifiers::default(),
1243 );
1244
1245 let clicks = captured.lock().unwrap();
1246 assert_eq!(clicks.len(), 3);
1247 assert_eq!(clicks[0].0, "https://example.com");
1248 assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
1249 assert!(clicks[0].1.modifiers().control);
1250 assert!(clicks[1].1.is_middle_click());
1251 assert!(clicks[2].1.is_right_click());
1252 assert_eq!(cx.opened_url(), None);
1253 }
1254
1255 #[gpui::test]
1256 fn linked_image_handler_receives_left_middle_and_right_clicks(cx: &mut TestAppContext) {
1257 use std::sync::{Arc, Mutex};
1258
1259 struct LinkedImageRoot {
1260 text_view: Entity<TextViewState>,
1261 clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
1262 }
1263
1264 impl Render for LinkedImageRoot {
1265 fn render(
1266 &mut self,
1267 _window: &mut Window,
1268 _cx: &mut Context<Self>,
1269 ) -> impl IntoElement {
1270 let clicks = self.clicks.clone();
1271 div().w(px(160.)).child(
1272 TextView::new(&self.text_view)
1273 .selectable(true)
1274 .on_link_click(move |url, event, _, _| {
1275 clicks.lock().unwrap().push((url.clone(), event.clone()));
1276 }),
1277 )
1278 }
1279 }
1280
1281 cx.update(crate::init);
1282 let clicks = Arc::new(Mutex::new(Vec::new()));
1283 let captured = clicks.clone();
1284 let (root, cx) = cx.add_window_view(move |window, cx| {
1285 let content = cx.new(|cx| LinkedImageRoot {
1286 text_view: cx.new(|cx| {
1287 TextViewState::markdown(
1288 r#"Before [<img src="https://example.com/image.svg" width="32" height="32">](https://example.com/image-link) after."#,
1289 cx,
1290 )
1291 }),
1292 clicks,
1293 });
1294 crate::Root::new(content, window, cx)
1295 });
1296 let content = root.read_with(cx, |root, _| {
1297 root.view().clone().downcast::<LinkedImageRoot>().unwrap()
1298 });
1299 let cx: &mut VisualTestContext = cx;
1300 cx.run_until_parked();
1301 cx.update(|window, cx| {
1302 let _ = window.draw(cx);
1303 });
1304
1305 let inline_bounds = content.read_with(cx, |content, cx| {
1306 content.text_view.read(cx).selection_adapter.text_bounds()
1307 });
1308 assert!(
1309 inline_bounds.len() >= 2,
1310 "linked image needs text bounds on both sides: {inline_bounds:?}"
1311 );
1312 assert!(
1313 inline_bounds[1].left() - inline_bounds[0].right() >= px(24.),
1314 "linked image did not reserve the expected click target: {inline_bounds:?}"
1315 );
1316 let position = point(
1317 inline_bounds[0].right() + (inline_bounds[1].left() - inline_bounds[0].right()) * 0.5,
1318 inline_bounds[0].top() + px(8.),
1319 );
1320 for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
1321 cx.simulate_mouse_down(position, button, Modifiers::default());
1322 cx.simulate_mouse_up(position, button, Modifiers::default());
1323 }
1324
1325 let clicks = captured.lock().unwrap();
1326 assert_eq!(clicks.len(), 3);
1327 assert!(
1328 clicks
1329 .iter()
1330 .all(|(url, _)| url == "https://example.com/image-link")
1331 );
1332 assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
1333 assert!(clicks[1].1.is_middle_click());
1334 assert!(clicks[2].1.is_right_click());
1335 assert_eq!(cx.opened_url(), None);
1336 }
1337
1338 #[gpui::test]
1339 fn clipped_markdown_cannot_start_selection(cx: &mut TestAppContext) {
1340 cx.update(crate::init);
1341 let (view, cx) = cx
1342 .add_window_view(|_, cx| TextViewTestRoot::new("visible\n\nhidden selection text", cx));
1343 let cx: &mut VisualTestContext = cx;
1344
1345 cx.simulate_mouse_down(
1346 point(px(10.), px(34.)),
1347 MouseButton::Left,
1348 Modifiers::default(),
1349 );
1350 cx.simulate_mouse_move(
1351 point(px(90.), px(34.)),
1352 Some(MouseButton::Left),
1353 Modifiers::default(),
1354 );
1355 cx.simulate_mouse_up(
1356 point(px(90.), px(34.)),
1357 MouseButton::Left,
1358 Modifiers::default(),
1359 );
1360
1361 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1362 assert!(
1363 selected_text.is_empty(),
1364 "unexpected selection: {selected_text:?}"
1365 );
1366 }
1367
1368 struct ClippedTallTextViewTestRoot {
1372 text_view: Entity<TextViewState>,
1373 }
1374
1375 impl ClippedTallTextViewTestRoot {
1376 fn new(cx: &mut Context<Self>) -> Self {
1377 let text_view =
1381 cx.new(|cx| TextViewState::markdown("alpha\n\nbravo\n\ncharlie\n\ndelta", cx));
1382 Self { text_view }
1383 }
1384 }
1385
1386 impl Render for ClippedTallTextViewTestRoot {
1387 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1388 div()
1389 .w(px(200.))
1390 .child(
1391 div()
1392 .h(px(40.))
1393 .overflow_hidden()
1394 .child(TextView::new(&self.text_view).selectable(true)),
1395 )
1396 .child(div().h(px(160.)))
1399 }
1400 }
1401
1402 #[gpui::test]
1411 fn selection_band_beyond_clip_copies_offscreen_text(cx: &mut TestAppContext) {
1412 cx.update(crate::init);
1413 let (view, cx) = cx.add_window_view(|window, cx| {
1414 let content = cx.new(ClippedTallTextViewTestRoot::new);
1415 crate::Root::new(content, window, cx)
1416 });
1417 let content = view.read_with(cx, |root, _| {
1418 root.view()
1419 .clone()
1420 .downcast::<ClippedTallTextViewTestRoot>()
1421 .unwrap()
1422 });
1423 let cx: &mut VisualTestContext = cx;
1424
1425 cx.run_until_parked();
1426 cx.update(|window, cx| {
1427 let _ = window.draw(cx);
1428 });
1429
1430 cx.simulate_mouse_down(
1434 point(px(2.), px(8.)),
1435 MouseButton::Left,
1436 Modifiers::default(),
1437 );
1438 cx.update(|window, cx| {
1439 let _ = window.draw(cx);
1440 });
1441 cx.simulate_mouse_move(
1442 point(px(180.), px(150.)),
1443 Some(MouseButton::Left),
1444 Modifiers::default(),
1445 );
1446 cx.update(|window, cx| {
1447 let _ = window.draw(cx);
1448 });
1449 cx.simulate_mouse_up(
1450 point(px(180.), px(150.)),
1451 MouseButton::Left,
1452 Modifiers::default(),
1453 );
1454 cx.update(|window, cx| {
1455 let _ = window.draw(cx);
1456 });
1457
1458 let selected_text =
1459 content.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1460 assert!(
1461 selected_text.contains("delta"),
1462 "clipped-out text was not copied: {selected_text:?}"
1463 );
1464 assert!(
1465 selected_text.contains("charlie"),
1466 "clipped-out text was not copied: {selected_text:?}"
1467 );
1468 }
1469
1470 #[gpui::test]
1471 fn double_click_selects_word(cx: &mut TestAppContext) {
1472 cx.update(crate::init);
1473 let (view, cx) =
1474 cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
1475
1476 let cx: &mut VisualTestContext = cx;
1477 cx.run_until_parked();
1478 cx.update(|window, cx| {
1479 let _ = window.draw(cx);
1480 });
1481 let position = point(px(10.), px(16.));
1482 cx.simulate_event(MouseDownEvent {
1483 position,
1484 modifiers: Modifiers::default(),
1485 button: MouseButton::Left,
1486 click_count: 2,
1487 first_mouse: false,
1488 });
1489 cx.simulate_event(MouseUpEvent {
1490 position,
1491 modifiers: Modifiers::default(),
1492 button: MouseButton::Left,
1493 click_count: 2,
1494 });
1495 cx.update(|window, cx| {
1496 let _ = window.draw(cx);
1497 });
1498
1499 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1500 assert_eq!(selected_text.trim(), "quick");
1501 }
1502
1503 #[gpui::test]
1504 fn triple_click_selects_paragraph(cx: &mut TestAppContext) {
1505 cx.update(crate::init);
1506 let (view, cx) =
1507 cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
1508
1509 let cx: &mut VisualTestContext = cx;
1510 cx.run_until_parked();
1511 cx.update(|window, cx| {
1512 let _ = window.draw(cx);
1513 });
1514
1515 let position = point(px(10.), px(10.));
1516 cx.simulate_event(MouseDownEvent {
1517 position,
1518 modifiers: Modifiers::default(),
1519 button: MouseButton::Left,
1520 click_count: 3,
1521 first_mouse: false,
1522 });
1523 cx.simulate_event(MouseUpEvent {
1524 position,
1525 modifiers: Modifiers::default(),
1526 button: MouseButton::Left,
1527 click_count: 3,
1528 });
1529 cx.update(|window, cx| {
1530 let _ = window.draw(cx);
1531 });
1532
1533 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1534 assert_eq!(selected_text.trim(), "quick select value");
1535 }
1536
1537 #[gpui::test]
1543 fn outer_list_content_total_stable_while_scrolling(cx: &mut TestAppContext) {
1544 use gpui::{ListAlignment, ListState, list};
1545
1546 const ITEMS: &[&str] = &[
1547 "# Heading\n\nA paragraph long enough to wrap across several lines and produce a non-trivial height.",
1548 "Short.",
1549 "Paragraph A\n\nParagraph B\n\nParagraph C with more words to increase the height.",
1550 "## Subheading\n\n- One\n- Two\n- Three\n\nClosing paragraph.",
1551 "Only one line.",
1552 "**Bold**: medium length text with `code` mixed with regular words.",
1553 "1. First\n2. Second\n3. Third\n\nA short closing paragraph.",
1554 "A long message with enough words to wrap across multiple lines, create a taller item, and verify that off-screen measurement matches visible measurement.",
1555 ];
1556 let n = 40usize;
1557
1558 struct ListRoot {
1559 state: ListState,
1560 }
1561 impl Render for ListRoot {
1562 fn render(&mut self, _w: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1563 div().w(px(360.)).h(px(500.)).child(
1564 list(self.state.clone(), |ix, _w, _cx| {
1565 div()
1566 .w_full()
1567 .child(TextView::markdown(
1568 ("md", ix as u64),
1569 ITEMS[ix % ITEMS.len()],
1570 ))
1571 .into_any_element()
1572 })
1573 .size_full(),
1574 )
1575 }
1576 }
1577
1578 cx.update(crate::init);
1579 let state = ListState::new(n, ListAlignment::Top, px(2048.)).measure_all();
1580 let probe = state.clone();
1581 let (_view, cx) = cx.add_window_view(|_w, _cx| ListRoot { state });
1582 let cx: &mut VisualTestContext = cx;
1583
1584 cx.run_until_parked();
1585 cx.update(|w, cx| {
1586 let _ = w.draw(cx);
1587 });
1588 cx.run_until_parked();
1589 cx.update(|w, cx| {
1590 let _ = w.draw(cx);
1591 });
1592
1593 let total = |p: &ListState| {
1594 f32::from(p.max_offset_for_scrollbar().y + p.viewport_bounds().size.height)
1595 };
1596 let mut totals = vec![total(&probe)];
1597 for _ in 0..20 {
1598 probe.scroll_by(px(150.));
1599 cx.update(|w, cx| {
1600 let _ = w.draw(cx);
1601 });
1602 cx.run_until_parked();
1603 totals.push(total(&probe));
1604 }
1605 let min = totals.iter().cloned().fold(f32::INFINITY, f32::min);
1606 let max = totals.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1607 println!(
1608 "OUTER_LIST_PROBE min={min:.1} max={max:.1} delta={:.1}",
1609 max - min
1610 );
1611 assert!(
1612 (max - min) < 2.0,
1613 "list content total jittered while scrolling: min={min} max={max} totals={totals:?}"
1614 );
1615 }
1616}