1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
5 AnyElement, AnyView, App, Bounds, ClickEvent, ContentMask, Element, ElementId, Entity, Global,
6 GlobalElementId, Hitbox, HitboxBehavior, Img, InspectorElementId, InteractiveElement,
7 IntoElement, LayoutId, MouseButton, ParentElement, Pixels, Refineable as _, SharedString,
8 Stateful, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, point, px,
9};
10
11use crate::StyledExt;
12use crate::input::a11y_text::A11yTextRuns;
13use crate::text::TextViewFormat;
14use crate::text::markdown_ext::{MarkdownExtensions, MarkdownNode, MarkdownPlugin};
15use crate::text::node::{CodeBlock, TableData};
16use crate::text::range_highlight::{PendingReveal, RevealProgress};
17use crate::text::state::{LineSpan, SelectionFormat, TextViewState};
18use crate::text::stream_fade::TextViewMotion;
19use crate::{GlobalState, TextSelection, text::TextViewStyle};
20
21pub(crate) type CodeBlockActionsFn =
23 dyn Fn(&CodeBlock, &mut Window, &mut App) -> AnyElement + Send + Sync;
24
25pub(crate) type CodeBlockHighlighterFn =
26 dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync;
27
28#[derive(Clone, Default)]
31pub struct TextViewDefaults {
32 style: Option<TextViewStyle>,
33 code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
34 inherit_text_color: bool,
35}
36
37impl Global for TextViewDefaults {}
38
39impl TextViewDefaults {
40 pub fn new() -> Self {
42 Self::default()
43 }
44
45 pub fn with_style(mut self, style: TextViewStyle) -> Self {
47 self.style = Some(style);
48 self
49 }
50
51 pub(crate) fn style(&self) -> Option<&TextViewStyle> {
53 self.style.as_ref()
54 }
55
56 pub(crate) fn code_block_highlighter(&self) -> Option<Arc<CodeBlockHighlighterFn>> {
58 self.code_block_highlighter.clone()
59 }
60
61 pub fn with_code_block_highlighter<F>(mut self, highlighter: F) -> Self
63 where
64 F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
65 {
66 self.code_block_highlighter = Some(Arc::new(highlighter));
67 self
68 }
69
70 pub fn with_inherit_text_color(mut self, inherit: bool) -> Self {
79 self.inherit_text_color = inherit;
80 self
81 }
82
83 pub fn install(self, cx: &mut App) {
85 cx.set_global(self);
86 }
87
88 pub fn global(cx: &App) -> Self {
90 cx.try_global::<Self>().cloned().unwrap_or_default()
91 }
92
93 pub fn has_code_block_highlighter(&self) -> bool {
95 self.code_block_highlighter.is_some()
96 }
97
98 pub fn inherit_text_color(&self) -> bool {
100 self.inherit_text_color
101 }
102}
103
104pub(crate) type TableActionsFn =
106 dyn Fn(&TableData, &mut Window, &mut App) -> AnyElement + Send + Sync;
107
108pub(crate) type ImageSourceFn = dyn Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync;
109
110pub(crate) type LinkFn = dyn Fn(&Link, &App) -> Option<Link> + Send + Sync;
111
112#[derive(Debug, Clone, PartialEq, Eq)]
118#[non_exhaustive]
119pub struct Link {
120 pub url: SharedString,
123 pub title: Option<SharedString>,
125}
126
127impl Link {
128 pub fn new(url: impl Into<SharedString>) -> Self {
130 Self {
131 url: url.into(),
132 title: None,
133 }
134 }
135
136 pub fn url(mut self, url: impl Into<SharedString>) -> Self {
138 self.url = url.into();
139 self
140 }
141
142 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
144 self.title = Some(title.into());
145 self
146 }
147}
148
149pub(crate) type LinkClickHandlerFn =
150 dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
151
152pub(crate) type LinkTooltipFn =
153 dyn Fn(&SharedString, &mut Window, &mut App) -> AnyView + Send + Sync;
154pub(crate) type TaskToggleHandlerFn = dyn Fn(&TaskToggleEvent, &mut Window, &mut App) + Send + Sync;
155
156#[derive(Debug, Clone)]
161pub struct TaskToggleEvent {
162 checked: bool,
163 item_range: Range<usize>,
164 marker_range: Range<usize>,
165}
166
167impl TaskToggleEvent {
168 pub(crate) fn new(checked: bool, item_range: Range<usize>, marker_range: Range<usize>) -> Self {
169 Self {
170 checked,
171 item_range,
172 marker_range,
173 }
174 }
175
176 pub fn checked(&self) -> bool {
179 self.checked
180 }
181
182 pub fn item_range(&self) -> Range<usize> {
185 self.item_range.clone()
186 }
187
188 pub fn marker_range(&self) -> Range<usize> {
190 self.marker_range.clone()
191 }
192}
193
194pub(crate) type RevealHandlerFn = dyn Fn(Bounds<Pixels>, &mut Window, &mut App);
197
198pub(super) fn linked_image(
200 image: Stateful<Img>,
201 url: SharedString,
202 click_handler: Option<Arc<LinkClickHandlerFn>>,
203) -> Stateful<Img> {
204 let aux_url = url.clone();
205 let aux_handler = click_handler.clone();
206 image
207 .cursor_pointer()
208 .on_click(move |event, window, cx| {
209 TextSelection::end(window, cx);
210 cx.stop_propagation();
211 handle_link_click(&click_handler, url.clone(), event.clone(), window, cx);
212 })
213 .on_aux_click(move |event, window, cx| {
214 TextSelection::end(window, cx);
215 cx.stop_propagation();
216 handle_link_click(&aux_handler, aux_url.clone(), event.clone(), window, cx);
217 })
218}
219
220pub(crate) fn handle_link_click(
221 handler: &Option<Arc<LinkClickHandlerFn>>,
222 url: SharedString,
223 event: ClickEvent,
224 window: &mut Window,
225 cx: &mut App,
226) {
227 if let Some(handler) = handler {
228 handler(&url, &event, window, cx);
229 } else if match &event {
230 ClickEvent::Mouse(click) => {
231 matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
232 }
233 ClickEvent::Keyboard(_) => true,
234 ClickEvent::Touch(click) => !click.long_press,
235 } {
236 cx.open_url(&url);
237 }
238}
239
240#[derive(Clone)]
257pub struct TextView {
258 id: ElementId,
259 format: Option<TextViewFormat>,
260 text: Option<SharedString>,
261 pub(crate) state: Option<Entity<TextViewState>>,
262 text_view_style: Option<TextViewStyle>,
263 inline_code_style: Option<StyleRefinement>,
264 list_style: Option<StyleRefinement>,
265 blockquote_style: Option<StyleRefinement>,
266 style: StyleRefinement,
267 selectable: bool,
268 selection_format: SelectionFormat,
269 scrollable: bool,
270 max_lines: Option<usize>,
271 code_block_actions: Option<Arc<CodeBlockActionsFn>>,
272 code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
273 table_actions: Option<Arc<TableActionsFn>>,
274 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
275 link_hook: Option<Arc<LinkFn>>,
276 link_tooltip: Option<Arc<LinkTooltipFn>>,
277 task_toggle_handler: Option<Arc<TaskToggleHandlerFn>>,
278 image_source: Option<Arc<ImageSourceFn>>,
279 reveal_handler: Option<Rc<RevealHandlerFn>>,
280 markdown_extensions: Arc<MarkdownExtensions>,
281 motion: Option<TextViewMotion>,
282}
283
284pub trait TextViewPlugin {
286 fn setup(self, text_view: TextView) -> TextView;
287}
288
289impl<P> TextViewPlugin for P
290where
291 P: MarkdownPlugin,
292{
293 fn setup(self, mut text_view: TextView) -> TextView {
294 let extensions = Arc::make_mut(&mut text_view.markdown_extensions);
295 let current = std::mem::take(extensions);
296 *extensions = current.plugin(self);
297 text_view
298 }
299}
300
301impl Styled for TextView {
302 fn style(&mut self) -> &mut StyleRefinement {
303 &mut self.style
304 }
305}
306
307impl TextView {
308 pub fn new(state: &Entity<TextViewState>) -> Self {
310 Self {
311 id: ElementId::Name(state.entity_id().to_string().into()),
312 state: Some(state.clone()),
313 format: None,
314 text: None,
315 text_view_style: None,
316 inline_code_style: None,
317 list_style: None,
318 blockquote_style: None,
319 style: StyleRefinement::default(),
320 selectable: true,
321 selection_format: SelectionFormat::default(),
322 scrollable: false,
323 max_lines: None,
324 code_block_actions: None,
325 code_block_highlighter: None,
326 table_actions: None,
327 link_click_handler: None,
328 link_hook: None,
329 link_tooltip: None,
330 task_toggle_handler: None,
331 image_source: None,
332 reveal_handler: None,
333 markdown_extensions: Arc::default(),
334 motion: None,
335 }
336 }
337
338 pub fn markdown(id: impl Into<ElementId>, markdown: impl Into<SharedString>) -> Self {
340 Self {
341 id: id.into(),
342 format: Some(TextViewFormat::Markdown),
343 text: Some(markdown.into()),
344 text_view_style: None,
345 inline_code_style: None,
346 list_style: None,
347 blockquote_style: None,
348 style: StyleRefinement::default(),
349 state: None,
350 selectable: true,
351 selection_format: SelectionFormat::default(),
352 scrollable: false,
353 max_lines: None,
354 code_block_actions: None,
355 code_block_highlighter: None,
356 table_actions: None,
357 link_click_handler: None,
358 link_hook: None,
359 link_tooltip: None,
360 task_toggle_handler: None,
361 image_source: None,
362 reveal_handler: None,
363 markdown_extensions: Arc::default(),
364 motion: None,
365 }
366 }
367
368 pub fn html(id: impl Into<ElementId>, html: impl Into<SharedString>) -> Self {
370 Self {
371 id: id.into(),
372 format: Some(TextViewFormat::Html),
373 text: Some(html.into()),
374 text_view_style: None,
375 inline_code_style: None,
376 list_style: None,
377 blockquote_style: None,
378 style: StyleRefinement::default(),
379 state: None,
380 selectable: true,
381 selection_format: SelectionFormat::default(),
382 scrollable: false,
383 max_lines: None,
384 code_block_actions: None,
385 code_block_highlighter: None,
386 table_actions: None,
387 link_click_handler: None,
388 link_hook: None,
389 link_tooltip: None,
390 task_toggle_handler: None,
391 image_source: None,
392 reveal_handler: None,
393 markdown_extensions: Arc::default(),
394 motion: None,
395 }
396 }
397
398 pub fn image_source<F>(mut self, resolver: F) -> Self
404 where
405 F: Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync + 'static,
406 {
407 self.image_source = Some(Arc::new(resolver));
408 self
409 }
410
411 pub fn inline_code_style(mut self, style: StyleRefinement) -> Self {
415 self.inline_code_style = Some(super::style::normalize_inline_code_style(style));
416 self
417 }
418
419 pub fn list_style(mut self, style: StyleRefinement) -> Self {
423 self.list_style = Some(style);
424 self
425 }
426
427 pub fn blockquote_style(mut self, style: StyleRefinement) -> Self {
431 self.blockquote_style = Some(style);
432 self
433 }
434
435 pub fn style(mut self, style: TextViewStyle) -> Self {
437 self.text_view_style = Some(style);
438 self
439 }
440
441 pub fn selectable(mut self, selectable: bool) -> Self {
448 self.selectable = selectable;
449 self
450 }
451
452 pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
457 self.selection_format = selection_format;
458 self
459 }
460
461 pub fn scrollable(mut self, scrollable: bool) -> Self {
474 self.scrollable = scrollable;
475 self
476 }
477
478 pub fn max_lines(mut self, max_lines: usize) -> Self {
497 self.max_lines = Some(max_lines);
498 self
499 }
500
501 pub fn code_block_actions<F, E>(mut self, f: F) -> Self
506 where
507 F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
508 E: IntoElement,
509 {
510 self.code_block_actions = Some(Arc::new(move |code_block, window, cx| {
511 f(&code_block, window, cx).into_any_element()
512 }));
513 self
514 }
515
516 pub fn code_block_highlighter<F>(mut self, highlighter: F) -> Self
521 where
522 F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
523 {
524 self.code_block_highlighter = Some(Arc::new(highlighter));
525 self
526 }
527
528 #[doc(hidden)]
535 pub fn shared_code_block_highlighter(
536 mut self,
537 highlighter: Arc<
538 dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync,
539 >,
540 ) -> Self {
541 self.code_block_highlighter = Some(highlighter);
542 self
543 }
544
545 pub fn table_actions<F, E>(mut self, f: F) -> Self
550 where
551 F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
552 E: IntoElement,
553 {
554 self.table_actions = Some(Arc::new(move |table, window, cx| {
555 f(table, window, cx).into_any_element()
556 }));
557 self
558 }
559
560 pub fn on_link_click<F>(mut self, handler: F) -> Self
565 where
566 F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
567 {
568 self.link_click_handler = Some(Arc::new(handler));
569 self
570 }
571
572 pub fn link<F>(mut self, f: F) -> Self
591 where
592 F: Fn(&Link, &App) -> Option<Link> + Send + Sync + 'static,
593 {
594 self.link_hook = Some(Arc::new(f));
595 self
596 }
597
598 pub fn link_tooltip<F>(mut self, builder: F) -> Self
603 where
604 F: Fn(&SharedString, &mut Window, &mut App) -> AnyView + Send + Sync + 'static,
605 {
606 self.link_tooltip = Some(Arc::new(builder));
607 self
608 }
609
610 pub fn on_task_toggle<F>(mut self, handler: F) -> Self
619 where
620 F: Fn(&TaskToggleEvent, &mut Window, &mut App) + Send + Sync + 'static,
621 {
622 self.task_toggle_handler = Some(Arc::new(handler));
623 self
624 }
625
626 pub fn on_reveal<F>(mut self, handler: F) -> Self
635 where
636 F: Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
637 {
638 self.reveal_handler = Some(Rc::new(handler));
639 self
640 }
641
642 pub fn markdown_extensions(mut self, extensions: MarkdownExtensions) -> Self {
644 self.markdown_extensions = Arc::new(extensions);
645 self
646 }
647
648 pub fn motion(mut self, motion: TextViewMotion) -> Self {
651 self.motion = Some(motion);
652 self
653 }
654
655 pub fn markdown_mdx(mut self) -> Self {
660 let extensions = Arc::make_mut(&mut self.markdown_extensions);
661 *extensions = extensions.clone().mdx();
662 self
663 }
664
665 pub fn markdown_raw_html(mut self, enabled: bool) -> Self {
668 let extensions = Arc::make_mut(&mut self.markdown_extensions);
669 *extensions = extensions.clone().raw_html(enabled);
670 self
671 }
672
673 pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
679 where
680 F: for<'a> Fn(
681 &markdown::mdast::Node,
682 &crate::text::MarkdownParseContext<'a>,
683 ) -> Option<MarkdownNode>
684 + Send
685 + Sync
686 + 'static,
687 {
688 Arc::make_mut(&mut self.markdown_extensions).push_block_parser(parser);
689 self
690 }
691
692 pub fn markdown_block_renderer<F, E>(
694 mut self,
695 name: impl Into<SharedString>,
696 renderer: F,
697 ) -> Self
698 where
699 F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
700 E: IntoElement,
701 {
702 Arc::make_mut(&mut self.markdown_extensions).push_block_renderer(name, renderer);
703 self
704 }
705
706 pub fn plugin<P>(self, plugin: P) -> Self
708 where
709 P: TextViewPlugin,
710 {
711 plugin.setup(self)
712 }
713}
714
715pub struct TextViewLayoutState {
716 state: Entity<TextViewState>,
717 element: AnyElement,
718}
719
720pub struct TextViewPrepaintState {
721 hitbox: Hitbox,
722 clip_bottom: Option<Pixels>,
726 touch_handles: crate::TouchHandleLayout,
728 a11y_text_runs: Option<Rc<A11yTextRuns>>,
731}
732
733const CLIP_EPSILON: Pixels = px(1.);
736
737fn last_line_bottom_above(spans: &[LineSpan], y: Pixels) -> Option<(Pixels, Pixels)> {
740 let mut last: Option<(Pixels, Pixels)> = None;
741 let mut keep = |bottom: Pixels, line_height: Pixels| {
742 if bottom <= y + CLIP_EPSILON && last.is_none_or(|(last, _)| bottom > last) {
743 last = Some((bottom, line_height));
744 }
745 };
746
747 for span in spans {
748 if span.line_height <= px(0.) {
749 continue;
750 }
751 let mut bottom = span.top + span.line_height;
752 while bottom <= span.bottom + CLIP_EPSILON {
753 keep(bottom, span.line_height);
754 bottom += span.line_height;
755 }
756 keep(span.bottom, span.line_height);
758 }
759
760 last
761}
762
763fn line_safe_clip_bottom(
773 spans: &[LineSpan],
774 box_bottom: Pixels,
775 content_bottom: Pixels,
776) -> Option<Pixels> {
777 let mut clip = box_bottom;
778
779 for span in spans {
780 if span.line_height <= px(0.)
781 || span.top >= box_bottom
782 || span.bottom <= box_bottom + CLIP_EPSILON
783 {
784 continue;
785 }
786 let whole_lines = ((box_bottom - span.top) / span.line_height).floor();
787 let line_top = span.top + span.line_height * whole_lines;
788 if line_top < box_bottom - CLIP_EPSILON {
790 clip = clip.min(line_top);
791 }
792 }
793
794 let Some((last_line_bottom, line_height)) = last_line_bottom_above(spans, clip) else {
795 return None;
800 };
801
802 if content_bottom > box_bottom + CLIP_EPSILON {
806 let strip = clip - last_line_bottom;
807 if strip > CLIP_EPSILON && strip < line_height {
808 clip = last_line_bottom;
809 }
810 }
811
812 (clip < box_bottom - CLIP_EPSILON).then_some(clip)
813}
814
815impl Element for TextView {
816 type RequestLayoutState = TextViewLayoutState;
817 type PrepaintState = TextViewPrepaintState;
818
819 fn id(&self) -> Option<ElementId> {
820 Some(self.id.clone())
821 }
822
823 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
824 None
825 }
826
827 fn a11y_role(&self) -> Option<gpui::Role> {
830 Some(gpui::Role::Document)
831 }
832
833 fn a11y_synthetic_children(
834 &mut self,
835 prepaint: &mut Self::PrepaintState,
836 builder: &mut gpui::A11ySubtreeBuilder,
837 ) {
838 if let Some(runs) = &prepaint.a11y_text_runs {
839 runs.push(builder);
840 }
841 }
842
843 fn request_layout(
844 &mut self,
845 _: Option<&GlobalElementId>,
846 _: Option<&InspectorElementId>,
847 window: &mut Window,
848 cx: &mut App,
849 ) -> (LayoutId, Self::RequestLayoutState) {
850 let state = if let Some(state) = self.state.clone() {
851 state
852 } else {
853 let default_format = self.format.unwrap_or(TextViewFormat::Markdown);
854 let default_text = self.text.clone().unwrap_or_default();
855
856 let state = window.use_keyed_state(
857 SharedString::from(format!("{}/state", self.id)),
858 cx,
859 move |_, cx| {
860 if default_format == TextViewFormat::Markdown {
861 TextViewState::markdown(default_text.as_str(), cx)
862 } else {
863 TextViewState::html(default_text.as_str(), cx)
864 }
865 },
866 );
867 self.state = Some(state.clone());
868 state
869 };
870
871 let max_lines = self.max_lines.filter(|_| !self.scrollable);
874
875 let defaults = cx.try_global::<TextViewDefaults>();
878 let theme_style;
879 let mut text_view_style = match (
880 &self.text_view_style,
881 defaults.and_then(|d| d.style.as_ref()),
882 ) {
883 (Some(style), _) | (None, Some(style)) => style,
884 (None, None) => {
885 theme_style = TextViewStyle::from_theme(&crate::Theme::global(cx));
886 &theme_style
887 }
888 };
889 let surface_style;
892 let mut on_inverted_surface = false;
893 if self.text_view_style.is_none() && defaults.is_some_and(|d| d.inherit_text_color) {
894 let color = self
895 .style
896 .text
897 .color
898 .unwrap_or_else(|| window.text_style().color);
899 if color != text_view_style.foreground() {
900 on_inverted_surface = text_view_style.is_inverted_by(color);
901 surface_style = text_view_style.on_text_color(color);
902 text_view_style = &surface_style;
903 }
904 }
905 let inline_style;
906 if let Some(refinement) = &self.inline_code_style {
907 let mut style = text_view_style.inline_code_style().clone();
908 style.refine(refinement);
909 inline_style = text_view_style.clone().with_inline_code_style(style);
910 text_view_style = &inline_style;
911 }
912 let block_style;
913 if self.list_style.is_some() || self.blockquote_style.is_some() {
914 let mut style = text_view_style.clone();
915 if let Some(refinement) = &self.list_style {
916 let mut marker = style.list_style().clone();
917 marker.refine(refinement);
918 style = style.with_list_style(marker);
919 }
920 if let Some(refinement) = &self.blockquote_style {
921 let mut quote = style.blockquote_style().clone();
922 quote.refine(refinement);
923 style = style.with_blockquote_style(quote);
924 }
925 block_style = style;
926 text_view_style = &block_style;
927 }
928 let foreground = text_view_style.foreground();
929 let text_view_style = (*state.read(cx).text_view_style != *text_view_style)
930 .then(|| Arc::new(text_view_style.clone()));
931 let code_block_highlighter = self.code_block_highlighter.clone().or_else(|| {
932 defaults
933 .filter(|_| !on_inverted_surface)
934 .and_then(|d| d.code_block_highlighter.clone())
935 });
936
937 state.update(cx, |state, cx| {
938 if text_view_style.is_some()
939 || match (&state.code_block_highlighter, &code_block_highlighter) {
940 (Some(previous), Some(next)) => !Arc::ptr_eq(previous, next),
941 (None, None) => false,
942 _ => true,
943 }
944 {
945 state.preserve_selection_for_reflow();
946 }
947 state.code_block_actions = self.code_block_actions.clone();
948 state.code_block_highlighter = code_block_highlighter;
949 state.table_actions = self.table_actions.clone();
950 state.link_click_handler = self.link_click_handler.clone();
951 state.link_hook = self.link_hook.clone();
952 state.link_tooltip = self.link_tooltip.clone();
953 state.task_toggle_handler = self.task_toggle_handler.clone();
954 state.image_source = self.image_source.clone();
955 state.set_markdown_extensions(self.markdown_extensions.clone(), cx);
956 if let Some(motion) = &self.motion {
957 state.set_motion(motion.clone());
958 }
959 state.selectable = self.selectable;
960 state.hover_cursor = self.style.mouse_cursor;
961 state.selection_format = self.selection_format;
962 state.scrollable = self.scrollable;
963 state.max_lines = max_lines;
964 if let Some(text_view_style) = text_view_style {
965 state.text_view_style = text_view_style;
966 }
967
968 if let Some(text) = &self.text {
969 state.set_element_text(text, cx);
970 }
971 });
972
973 let focus_handle = state.read(cx).focus_handle.clone();
974 let list_state = state.read(cx).list_state.clone();
975 let max_lines_cap = max_lines.map(|max_lines| {
979 let mut text_style = window.text_style();
980 text_style.refine(&self.style.text);
981 text_style.line_height_in_pixels(window.rem_size()) * max_lines as f32
982 });
983
984 let mut el = div()
985 .id(("text-view-scroll", state.entity_id()))
986 .key_context("TextView")
987 .track_focus(&focus_handle)
988 .when(self.scrollable, |this| this.size_full())
989 .when_some(max_lines_cap, |this, cap| this.max_h(cap).overflow_hidden())
990 .relative()
991 .when(crate::LayoutDirection::global(cx).is_rtl(), |this| {
994 crate::LogicalStyledExt::text_start(this, cx)
995 })
996 .text_color(foreground)
997 .on_action(move |_: &crate::input::Copy, window, cx| {
998 let text = TextSelection::selected_text(window, cx).trim().to_string();
999 if text.is_empty() {
1000 cx.propagate();
1001 return;
1002 }
1003 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
1004 })
1005 .on_action(window.listener_for(&state, TextViewState::on_action_select_all))
1006 .map(|this| {
1007 if self.scrollable {
1008 this.child(crate::ScrollBounce::new(
1009 ("text-view-bounce", state.entity_id()),
1010 &list_state,
1011 state.clone(),
1012 ))
1013 } else {
1014 this.child(state.clone())
1015 }
1016 })
1017 .when(self.scrollable, |this| {
1020 this.child(
1021 div().absolute().inset_0().child(
1022 crate::Scrollbar::vertical(&list_state)
1023 .id(("text-view-scrollbar", state.entity_id()))
1024 .viewport_from_layout(),
1025 ),
1026 )
1027 })
1028 .refine_style(&self.style)
1029 .into_any_element();
1030 let layout_id = el.request_layout(window, cx);
1031 (layout_id, TextViewLayoutState { state, element: el })
1032 }
1033
1034 fn prepaint(
1035 &mut self,
1036 _: Option<&GlobalElementId>,
1037 _: Option<&InspectorElementId>,
1038 bounds: Bounds<Pixels>,
1039 request_layout: &mut Self::RequestLayoutState,
1040 window: &mut Window,
1041 cx: &mut App,
1042 ) -> Self::PrepaintState {
1043 let state = request_layout.state.clone();
1044 let max_lines_active = state.read(cx).max_lines.is_some();
1045 if max_lines_active {
1046 if let Ok(mut line_spans) = state.read(cx).line_spans.lock() {
1047 line_spans.clear();
1048 }
1049 }
1050 GlobalState::global(cx).push_text_view_state(state.clone());
1055 request_layout.element.prepaint(window, cx);
1056 GlobalState::global(cx).pop_text_view_state();
1057
1058 let mut clip_bottom = None;
1059 if max_lines_active {
1060 let (line_spans, content_bottom) = {
1061 let state = state.read(cx);
1062 (
1063 state
1064 .line_spans
1065 .lock()
1066 .map(|spans| spans.clone())
1067 .unwrap_or_default(),
1068 state.bounds().bottom(),
1069 )
1070 };
1071 let clipped = content_bottom > bounds.bottom() + px(1.);
1075 if state.read(cx).clamped != clipped {
1078 state.update(cx, |state, cx| {
1079 state.clamped = clipped;
1080 cx.notify();
1081 });
1082 }
1083 if clipped {
1084 clip_bottom = line_safe_clip_bottom(&line_spans, bounds.bottom(), content_bottom);
1085 }
1086 }
1087
1088 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1089 let touch_handles = if self.selectable {
1091 state
1092 .read(cx)
1093 .selection_adapter
1094 .prepaint_touch_handles(window, cx)
1095 } else {
1096 crate::TouchHandleLayout::default()
1097 };
1098 let a11y_text_runs = window
1099 .is_a11y_active()
1100 .then(|| {
1101 let scale = window.scale_factor();
1102 state.update(cx, |state, _| state.accessibility_text_runs(scale))
1103 })
1104 .flatten();
1105 TextViewPrepaintState {
1106 hitbox,
1107 clip_bottom,
1108 touch_handles,
1109 a11y_text_runs,
1110 }
1111 }
1112
1113 fn paint(
1114 &mut self,
1115 _: Option<&GlobalElementId>,
1116 _: Option<&InspectorElementId>,
1117 bounds: Bounds<Pixels>,
1118 request_layout: &mut Self::RequestLayoutState,
1119 prepaint: &mut Self::PrepaintState,
1120 window: &mut Window,
1121 cx: &mut App,
1122 ) {
1123 let state = &request_layout.state;
1124 if self.selectable {
1125 state.read(cx).selection_adapter.begin_frame();
1126 }
1127
1128 GlobalState::global(cx).push_text_view_state(state.clone());
1129 if let Some(clip_bottom) = prepaint.clip_bottom {
1130 let mask = ContentMask {
1133 bounds: Bounds::from_corners(bounds.origin, point(bounds.right(), clip_bottom)),
1134 };
1135 window.with_content_mask(Some(mask), |window| {
1136 request_layout.element.paint(window, cx);
1137 });
1138 } else {
1139 request_layout.element.paint(window, cx);
1140 }
1141 GlobalState::global(cx).pop_text_view_state();
1142
1143 if state.read(cx).pending_reveal.is_some() {
1146 let progress = state.update(cx, |state, _| {
1147 state.pending_reveal.as_mut().map(PendingReveal::progress)
1148 });
1149 match progress {
1150 Some(RevealProgress::Shown) => {
1151 state.update(cx, |state, _| state.pending_reveal = None);
1152 }
1153 Some(RevealProgress::Hidden(line)) => {
1154 if let Some(handler) = &self.reveal_handler {
1155 handler(line, window, cx);
1156 }
1157 }
1158 Some(RevealProgress::NotLaidOut) | None => {}
1159 }
1160 }
1161
1162 if self.selectable {
1163 let (adapter, scroll_offset, content_bounds, self_scroll, handle_color) = {
1164 let state = state.read(cx);
1165 (
1166 state.selection_adapter.clone(),
1167 state.scroll_offset(),
1168 state.bounds(),
1169 state.scrollable,
1170 state.text_view_style.selection().alpha(1.),
1171 )
1172 };
1173 adapter.register(
1174 prepaint.hitbox.clone(),
1175 content_bounds,
1176 scroll_offset,
1177 self_scroll,
1178 window,
1179 cx,
1180 );
1181 adapter.paint_touch_handles(&prepaint.touch_handles, handle_color, window, cx);
1184 }
1185 }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190 use std::sync::{
1191 Arc,
1192 atomic::{AtomicUsize, Ordering},
1193 };
1194
1195 use super::{TaskToggleEvent, TextView, TextViewPlugin};
1196 use crate::text::{SelectionFormat, TableData, TextViewState, TextViewStyle};
1197 use gpui::{
1198 AppContext as _, Bounds, ClickEvent, Context, CursorStyle, Entity, InteractiveElement as _,
1199 IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Overflow,
1200 ParentElement as _, Pixels, Render, SharedString, StatefulInteractiveElement as _,
1201 StyleRefinement, Styled as _, TestAppContext, VisualTestContext, Window, div, point,
1202 prelude::FluentBuilder as _, px, rems,
1203 };
1204
1205 struct TextViewTestRoot {
1206 text_view: Entity<TextViewState>,
1207 }
1208
1209 struct InlineHoverTestRoot {
1210 view: Entity<TextViewState>,
1211 builds: Arc<AtomicUsize>,
1212 format: crate::text::SelectionFormat,
1213 }
1214
1215 struct InlineHoverCard;
1216 impl Render for InlineHoverCard {
1217 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1218 div()
1219 .debug_selector(|| "inline-test-card".into())
1220 .w(px(120.))
1221 .h(px(40.))
1222 .child("Member profile")
1223 }
1224 }
1225
1226 impl Render for InlineHoverTestRoot {
1227 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1228 let builds = self.builds.clone();
1229 div()
1230 .pl(px(150.))
1231 .w(px(300.))
1232 .text_size(px(16.))
1233 .child(crate::TextSelectionLayer)
1234 .child(
1235 TextView::new(&self.view)
1236 .selection_format(self.format)
1237 .plugin(
1238 crate::text::markdown_ext::TestInlinePlugin::new("mention")
1239 .parse_with(|node, _| {
1240 let markdown::mdast::Node::Link(link) = node else {
1241 return None;
1242 };
1243 let handle = link.url.strip_prefix("mention:")?;
1244 Some(
1245 crate::text::MarkdownNode::new("mention", ())
1246 .text(format!("@{handle}")),
1247 )
1248 })
1249 .render_with(move |_, _, _, _| {
1250 let builds = builds.clone();
1251 Some(crate::text::InlineElement::new(
1252 crate::HoverCard::new("mention-hover")
1253 .anchor(gpui::Anchor::TopCenter)
1254 .trigger(div().child("@member"))
1255 .content(move |_, _, cx| {
1256 builds.fetch_add(1, Ordering::Relaxed);
1257 div()
1258 .id("hover-content")
1259 .child(cx.new(|_| InlineHoverCard))
1260 }),
1261 ))
1262 }),
1263 ),
1264 )
1265 }
1266 }
1267
1268 #[gpui::test]
1269 fn text_view_follows_the_text_color_of_its_container(cx: &mut TestAppContext) {
1270 struct Root {
1271 inherited: Entity<TextViewState>,
1272 explicit: Entity<TextViewState>,
1273 surface_text: gpui::Hsla,
1274 }
1275 impl Render for Root {
1276 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1277 div()
1278 .w(px(300.))
1279 .text_color(crate::ColorTokens::light().foreground)
1280 .child(
1281 div()
1282 .text_color(self.surface_text)
1283 .child(TextView::new(&self.inherited))
1284 .child(TextView::new(&self.explicit).style(TextViewStyle::default())),
1285 )
1286 }
1287 }
1288
1289 let colors = crate::ColorTokens::light();
1290 cx.update(|cx| {
1291 crate::init(cx);
1292 super::TextViewDefaults::new()
1293 .with_style(TextViewStyle::default())
1294 .with_inherit_text_color(true)
1295 .install(cx);
1296 });
1297 let (root, cx) = cx.add_window_view(|_, cx| Root {
1298 inherited: cx.new(|cx| TextViewState::markdown("[link](https://a.b) `code`", cx)),
1299 explicit: cx.new(|cx| TextViewState::markdown("text", cx)),
1300 surface_text: colors.primary_foreground,
1301 });
1302 cx.run_until_parked();
1303 cx.update(|window, cx| {
1304 window.draw(cx).clear(cx);
1305 });
1306
1307 root.read_with(cx, |root, cx| {
1308 let inherited = &root.inherited.read(cx).text_view_style;
1309 assert_eq!(inherited.foreground(), colors.primary_foreground);
1310 assert_eq!(inherited.link(), colors.primary_foreground);
1311 assert!(inherited.is_dark());
1312
1313 let explicit = &root.explicit.read(cx).text_view_style;
1314 assert_eq!(explicit.foreground(), colors.foreground);
1315 assert_eq!(explicit.link(), TextViewStyle::default().link());
1316 });
1317 }
1318
1319 #[gpui::test]
1320 fn inline_plugin_reuses_render_and_preserves_native_child_events(cx: &mut TestAppContext) {
1321 use std::sync::Mutex;
1322 struct ControlPlugin(Arc<Mutex<Vec<String>>>);
1323 impl crate::text::MarkdownPlugin for ControlPlugin {
1324 fn name(&self) -> &str {
1325 "control"
1326 }
1327 fn parse(
1328 &self,
1329 node: &markdown::mdast::Node,
1330 _: &crate::text::MarkdownParseContext<'_>,
1331 ) -> Option<crate::text::MarkdownNode> {
1332 let markdown::mdast::Node::Link(link) = node else {
1333 return None;
1334 };
1335 let label = link.url.strip_prefix("control:")?;
1336 Some(crate::text::MarkdownNode::new("control", ()).text(label.to_string()))
1337 }
1338 fn render(
1339 &self,
1340 node: &crate::text::MarkdownNode,
1341 _: &mut Window,
1342 _: &mut gpui::App,
1343 ) -> impl IntoElement {
1344 let clicks = self.0.clone();
1345 let label = node.as_text().to_string();
1346 div()
1347 .id("same-control-id")
1348 .w(px(60.))
1349 .h(px(24.))
1350 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1351 .on_click(move |_, _, _| clicks.lock().unwrap().push(label.clone()))
1352 .child(node.as_text().to_string())
1353 }
1354 }
1355 struct Root {
1356 view: Entity<TextViewState>,
1357 clicks: Arc<Mutex<Vec<String>>>,
1358 }
1359 impl Render for Root {
1360 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1361 div()
1362 .w(px(300.))
1363 .child(crate::TextSelectionLayer)
1364 .child(TextView::new(&self.view).plugin(ControlPlugin(self.clicks.clone())))
1365 }
1366 }
1367 cx.update(crate::init);
1368 let clicks = Arc::new(Mutex::new(Vec::new()));
1369 let captured = clicks.clone();
1370 let (root, cx) = cx.add_window_view(move |_, cx| Root {
1371 view: cx.new(|cx| TextViewState::markdown("[one](control:one)[two](control:two)", cx)),
1372 clicks,
1373 });
1374 cx.run_until_parked();
1375 cx.update(|window, cx| {
1376 window.draw(cx).clear(cx);
1377 });
1378 let bounds = root.read_with(cx, |root, cx| {
1379 root.view.read(cx).selection_adapter.text_bounds()
1380 });
1381 assert_eq!(bounds.len(), 2);
1382 for bounds in bounds {
1383 cx.simulate_click(bounds.center(), Modifiers::default());
1384 cx.update(|window, cx| {
1385 window.draw(cx).clear(cx);
1386 });
1387 }
1388 assert_eq!(*captured.lock().unwrap(), vec!["one", "two"]);
1389 }
1390
1391 #[gpui::test]
1392 fn inline_hover_card_is_lazy_and_retains_atomic_copy(cx: &mut TestAppContext) {
1393 cx.update(crate::init);
1394 let builds = Arc::new(AtomicUsize::new(0));
1395 let source = "[@member](mention:member)";
1396 let (root, cx) = cx.add_window_view(|_, cx| InlineHoverTestRoot {
1397 view: cx.new(|cx| TextViewState::markdown(source, cx)),
1398 builds: builds.clone(),
1399 format: crate::text::SelectionFormat::Plain,
1400 });
1401 cx.run_until_parked();
1402 cx.update(|window, cx| window.draw(cx).clear(cx));
1403 assert_eq!(builds.load(Ordering::Relaxed), 0);
1404 let view = root.read_with(cx, |root, _| root.view.clone());
1405 let bounds = view.read_with(cx, |view, _| view.selection_adapter.text_bounds()[0]);
1406 cx.update(|window, cx| {
1407 window.simulate_mouse_move(point(bounds.right() - px(1.), bounds.center().y), cx)
1408 });
1409 cx.run_until_parked();
1410 cx.executor()
1411 .advance_clock(std::time::Duration::from_secs(1));
1412 cx.run_until_parked();
1413 cx.update(|window, cx| window.draw(cx).clear(cx));
1414 assert!(
1415 builds.load(Ordering::Relaxed) > 0,
1416 "hover did not build the card"
1417 );
1418 cx.update(|window, cx| window.draw(cx).clear(cx));
1419 let card = cx
1420 .debug_bounds("inline-test-card")
1421 .expect("hover card should be painted");
1422 assert!(
1423 (card.center().x - bounds.center().x).abs() < px(1.),
1424 "card {card:?} must be centered on mention {bounds:?}"
1425 );
1426 assert!(
1427 card.top() >= bounds.bottom(),
1428 "card should be below the mention"
1429 );
1430 for (format, expected) in [
1431 (crate::text::SelectionFormat::Plain, "@member"),
1432 (crate::text::SelectionFormat::Source, source),
1433 ] {
1434 root.update(cx, |root, cx| {
1435 root.format = format;
1436 cx.notify();
1437 });
1438 view.update(cx, |view, cx| {
1439 view.set_selection_format(format, cx);
1440 view.select_all(cx);
1441 });
1442 cx.update(|window, cx| window.draw(cx).clear(cx));
1443 assert_eq!(
1444 view.read_with(cx, |view, _| view.selected_text()).trim(),
1445 expected
1446 );
1447 }
1448 }
1449
1450 struct InlinePluginTestRoot {
1451 text_view: Entity<TextViewState>,
1452 width: Pixels,
1453 font_size: Pixels,
1454 source_format: bool,
1455 prepared_size: Option<Arc<AtomicUsize>>,
1456 }
1457
1458 impl Render for InlinePluginTestRoot {
1459 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1460 let prepared_size = self.prepared_size.clone();
1461 div().w(self.width).text_size(self.font_size).child(crate::TextSelectionLayer).child(
1462 TextView::new(&self.text_view)
1463 .selection_format(if self.source_format { crate::text::SelectionFormat::Source }
1464 else { crate::text::SelectionFormat::Plain })
1465
1466 .plugin(crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(|node, _| {
1467 let markdown::mdast::Node::InlineMath(math) = node else { return None };
1468 Some(crate::text::MarkdownNode::new("math", ()).text(format!("{}²", math.value)))
1469 }).render_with(move |_, context, _, _| {
1470 let value = prepared_size.as_ref()?.load(Ordering::Relaxed) as f32;
1471 let image = Arc::new(gpui::Image::from_bytes(gpui::ImageFormat::Svg,
1472 b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"40\"><path d=\"M0 0L40 40\" stroke=\"black\"/></svg>".to_vec()));
1473 let unit = context.font_size() / 16.;
1474 Some(crate::text::InlineElement::new(gpui::img(image).w(unit * value).h(unit * value)).with_baseline(unit * value * 0.75))
1475 })))
1476 }
1477 }
1478
1479 #[gpui::test]
1480 fn inline_plugins_drag_and_copy_across_formulas_in_both_directions(cx: &mut TestAppContext) {
1481 cx.update(crate::init);
1482 let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1483 text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1484 width: px(420.),
1485 font_size: px(16.),
1486 source_format: false,
1487 prepared_size: None,
1488 });
1489 let cx: &mut VisualTestContext = cx;
1490 for font_size in [16., 24., 32.] {
1491 for width in [60., 160., 420.] {
1492 for prepared in [None, Some(32)] {
1493 for source_format in [false, true] {
1494 root.update(cx, |root, cx| {
1495 root.source_format = source_format;
1496 root.width = px(width);
1497 root.font_size = px(font_size);
1498 root.prepared_size =
1499 prepared.map(|value| Arc::new(AtomicUsize::new(value)));
1500 cx.notify();
1501 });
1502 cx.run_until_parked();
1503 cx.update(|window, cx| window.draw(cx).clear(cx));
1504 let bounds =
1505 root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1506 let text_bounds = root.read_with(cx, |root, cx| {
1507 root.text_view.read(cx).selection_adapter.text_bounds()
1508 });
1509 let first = text_bounds.first().unwrap();
1510 let last = text_bounds.last().unwrap();
1511 let left =
1512 point(first.left() + px(0.1), first.top() + first.size.height / 2.);
1513 let right =
1514 point(last.right() - px(0.1), last.top() + last.size.height / 2.);
1515 for (start, end) in [(left, right), (right, left)] {
1516 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1517 cx.update(|window, cx| window.draw(cx).clear(cx));
1518 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1519 cx.update(|window, cx| window.draw(cx).clear(cx));
1520 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1521 cx.update(|window, cx| window.draw(cx).clear(cx));
1522 let selected = root
1523 .read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1524 assert_eq!(
1525 selected.trim(),
1526 if source_format {
1527 "中文 $x$ $y$ English"
1528 } else {
1529 "中文 x² y² English"
1530 },
1531 "start={start:?} end={end:?} bounds={bounds:?} width={width} font_size={font_size} prepared={prepared:?}"
1532 );
1533 }
1534 }
1535 }
1536 }
1537 }
1538 }
1539
1540 #[gpui::test]
1541 fn inline_resource_size_update_reflows_without_changing_selection(cx: &mut TestAppContext) {
1542 cx.update(crate::init);
1543 let prepared_size = Arc::new(AtomicUsize::new(16));
1544 let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1545 text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1546 width: px(160.),
1547 font_size: px(16.),
1548 source_format: false,
1549 prepared_size: Some(prepared_size.clone()),
1550 });
1551 let cx: &mut VisualTestContext = cx;
1552 cx.run_until_parked();
1553 cx.update(|window, cx| window.draw(cx).clear(cx));
1554 let before = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1555 let regions = root.read_with(cx, |root, cx| {
1556 root.text_view.read(cx).selection_adapter.text_bounds()
1557 });
1558 let first = regions.first().unwrap();
1559 let last = regions.last().unwrap();
1560 let start = point(first.left() + px(0.1), first.top() + px(10.));
1561 let end = point(last.right() - px(0.1), last.top() + px(10.));
1562 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1563 cx.update(|window, cx| window.draw(cx).clear(cx));
1564 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1565 cx.update(|window, cx| window.draw(cx).clear(cx));
1566 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1567 cx.update(|window, cx| window.draw(cx).clear(cx));
1568 assert_eq!(
1569 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1570 .trim(),
1571 "中文 x² y² English"
1572 );
1573 prepared_size.store(100, Ordering::Relaxed);
1574 root.update(cx, |root, cx| {
1575 root.text_view
1576 .update(cx, |state, cx| state.invalidate_inline_layout(cx))
1577 });
1578 cx.run_until_parked();
1579 cx.update(|window, cx| window.draw(cx).clear(cx));
1580 let after = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1581 assert!(after.size.height > before.size.height * 2.);
1582 assert_eq!(
1583 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1584 .trim(),
1585 "中文 x² y² English"
1586 );
1587 }
1588
1589 #[gpui::test]
1590 fn triple_click_on_formula_selects_its_entire_mixed_line(cx: &mut TestAppContext) {
1591 cx.update(crate::init);
1592 let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1593 text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1594 width: px(420.),
1595 font_size: px(16.),
1596 source_format: false,
1597 prepared_size: None,
1598 });
1599 let cx: &mut VisualTestContext = cx;
1600 cx.run_until_parked();
1601 cx.update(|window, cx| window.draw(cx).clear(cx));
1602 let regions = root.read_with(cx, |root, cx| {
1603 root.text_view.read(cx).selection_adapter.text_bounds()
1604 });
1605 let formula = regions[1];
1606 let position = formula.center();
1607 cx.simulate_event(MouseDownEvent {
1608 position,
1609 modifiers: Modifiers::default(),
1610 button: MouseButton::Left,
1611 click_count: 3,
1612 first_mouse: false,
1613 });
1614 cx.simulate_event(MouseUpEvent {
1615 position,
1616 modifiers: Modifiers::default(),
1617 button: MouseButton::Left,
1618 click_count: 3,
1619 });
1620 cx.update(|window, cx| window.draw(cx).clear(cx));
1621 assert_eq!(
1622 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1623 .trim(),
1624 "before x² after"
1625 );
1626 root.update(cx, |root, cx| {
1627 root.source_format = true;
1628 cx.notify();
1629 });
1630 cx.update(|window, cx| window.draw(cx).clear(cx));
1631 assert_eq!(
1632 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1633 .trim(),
1634 "before $x$ after"
1635 );
1636 }
1637
1638 fn triple_click_second_row(markdown: &'static str, cx: &mut TestAppContext) -> String {
1641 cx.update(crate::init);
1642 let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1643 text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
1644 width: px(160.),
1645 font_size: px(16.),
1646 source_format: false,
1647 prepared_size: None,
1648 });
1649 let cx: &mut VisualTestContext = cx;
1650 cx.run_until_parked();
1651 cx.update(|window, cx| window.draw(cx).clear(cx));
1652 let regions = root.read_with(cx, |root, cx| {
1653 root.text_view.read(cx).selection_adapter.text_bounds()
1654 });
1655 let first_top = regions[0].top();
1656 let second_row = regions
1657 .iter()
1658 .filter(|region| region.top() > first_top + px(4.))
1659 .min_by(|a, b| a.top().partial_cmp(&b.top()).unwrap())
1660 .copied()
1661 .expect("the paragraph wraps");
1662 let position = second_row.center();
1663 cx.simulate_event(MouseDownEvent {
1664 position,
1665 modifiers: Modifiers::default(),
1666 button: MouseButton::Left,
1667 click_count: 3,
1668 first_mouse: false,
1669 });
1670 cx.simulate_event(MouseUpEvent {
1671 position,
1672 modifiers: Modifiers::default(),
1673 button: MouseButton::Left,
1674 click_count: 3,
1675 });
1676 cx.update(|window, cx| window.draw(cx).clear(cx));
1677 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1678 .trim()
1679 .to_string()
1680 }
1681
1682 #[gpui::test]
1683 fn triple_click_selects_a_wrapped_paragraph_with_inline_code(cx: &mut TestAppContext) {
1684 assert_eq!(
1685 triple_click_second_row(
1686 "Call `foo` now, then keep typing until this paragraph wraps onto a few rows.\n\nNext paragraph.",
1687 cx,
1688 ),
1689 "Call foo now, then keep typing until this paragraph wraps onto a few rows."
1690 );
1691 }
1692
1693 #[gpui::test]
1694 fn triple_click_selects_a_wrapped_paragraph_with_several_inline_nodes(cx: &mut TestAppContext) {
1695 assert_eq!(
1696 triple_click_second_row(
1697 "Call `foo` and **bold** then `bar` with $x$ until this paragraph wraps onto rows.\n\nNext paragraph.",
1698 cx,
1699 ),
1700 "Call foo and bold then bar with x² until this paragraph wraps onto rows."
1701 );
1702 }
1703
1704 #[gpui::test]
1705 fn triple_click_selects_a_wrapped_plain_paragraph(cx: &mut TestAppContext) {
1706 assert_eq!(
1707 triple_click_second_row(
1708 "Plain words keep going until this paragraph wraps onto a few rows.\n\nNext paragraph.",
1709 cx,
1710 ),
1711 "Plain words keep going until this paragraph wraps onto a few rows."
1712 );
1713 }
1714
1715 #[gpui::test]
1716 fn double_click_on_formula_selects_only_that_object(cx: &mut TestAppContext) {
1717 cx.update(crate::init);
1718 let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1719 text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1720 width: px(420.),
1721 font_size: px(16.),
1722 source_format: false,
1723 prepared_size: None,
1724 });
1725 let cx: &mut VisualTestContext = cx;
1726 cx.run_until_parked();
1727 cx.update(|window, cx| window.draw(cx).clear(cx));
1728 let regions = root.read_with(cx, |root, cx| {
1729 root.text_view.read(cx).selection_adapter.text_bounds()
1730 });
1731 let position = regions[1].center();
1732 cx.simulate_event(MouseDownEvent {
1733 position,
1734 modifiers: Modifiers::default(),
1735 button: MouseButton::Left,
1736 click_count: 2,
1737 first_mouse: false,
1738 });
1739 cx.simulate_event(MouseUpEvent {
1740 position,
1741 modifiers: Modifiers::default(),
1742 button: MouseButton::Left,
1743 click_count: 2,
1744 });
1745 cx.update(|window, cx| window.draw(cx).clear(cx));
1746 assert_eq!(
1748 root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1749 .trim(),
1750 "x²"
1751 );
1752 }
1753
1754 struct ScrollExtentTestRoot {
1757 text_view: Entity<TextViewState>,
1758 }
1759
1760 impl Render for ScrollExtentTestRoot {
1761 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1762 div()
1763 .w(px(400.))
1764 .h(px(200.))
1765 .overflow_hidden()
1766 .child(TextView::new(&self.text_view).scrollable(true))
1767 }
1768 }
1769
1770 fn document_of(count: usize, words: usize) -> String {
1773 (1..=count)
1774 .map(|i| format!("Block {i}: {}", "lorem ipsum dolor ".repeat(words)))
1775 .collect::<Vec<_>>()
1776 .join("\n\n")
1777 }
1778
1779 #[gpui::test]
1785 fn replacing_a_document_with_an_equal_block_count_remeasures(cx: &mut TestAppContext) {
1786 cx.update(crate::init);
1787
1788 const BLOCKS: usize = 24;
1789 let short = document_of(BLOCKS, 1);
1790 let tall = document_of(BLOCKS, 60);
1791
1792 let (root, cx) = cx.add_window_view(|_, cx| ScrollExtentTestRoot {
1793 text_view: cx.new(|cx| TextViewState::markdown(&short, cx)),
1794 });
1795 let cx: &mut VisualTestContext = cx;
1796
1797 let settle = |cx: &mut VisualTestContext| {
1800 cx.run_until_parked();
1801 cx.update(|window, cx| window.draw(cx).clear(cx));
1802 cx.run_until_parked();
1803 };
1804 settle(cx);
1805
1806 let scroll_extent = |cx: &mut VisualTestContext| {
1807 root.read_with(cx, |root, cx| {
1808 root.text_view
1809 .read(cx)
1810 .list_state()
1811 .max_offset_for_scrollbar()
1812 .y
1813 })
1814 };
1815
1816 let short_extent = scroll_extent(cx);
1817
1818 root.update(cx, |root, cx| {
1819 root.text_view
1820 .update(cx, |state, cx| state.set_text(&tall, cx));
1821 });
1822 settle(cx);
1823
1824 root.read_with(cx, |root, cx| {
1825 assert_eq!(
1826 root.text_view.read(cx).list_state().item_count(),
1827 BLOCKS,
1828 "the replacement must keep the block count, or the list resets and the bug cannot occur"
1829 );
1830 });
1831
1832 let tall_extent = scroll_extent(cx);
1833 assert!(
1834 tall_extent > short_extent * 5.,
1835 "a much taller document must grow the scroll extent, but it went from \
1836 {short_extent:?} to {tall_extent:?}"
1837 );
1838 }
1839
1840 struct StatelessMarkdownRoot {
1841 renders: Arc<AtomicUsize>,
1842 }
1843
1844 impl Render for StatelessMarkdownRoot {
1845 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1846 self.renders.fetch_add(1, Ordering::Relaxed);
1847 div().child(
1848 TextView::markdown("stateless-markdown", include_str!("../../../../README.md"))
1849 .markdown_block_parser(|_, _| None),
1850 )
1851 }
1852 }
1853
1854 struct DummyTextViewPlugin;
1855
1856 impl TextViewPlugin for DummyTextViewPlugin {
1857 fn setup(self, mut text_view: TextView) -> TextView {
1858 text_view.selectable = true;
1859 text_view
1860 }
1861 }
1862
1863 #[gpui::test]
1864 fn text_view_constructors_are_selectable_by_default(cx: &mut TestAppContext) {
1865 cx.update(crate::init);
1866 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1867
1868 assert!(TextView::new(&state).selectable);
1869 assert!(TextView::markdown("markdown", "text").selectable);
1870 assert!(TextView::html("html", "<p>text</p>").selectable);
1871 }
1872
1873 #[gpui::test]
1874 fn cursor_on_text_view_replaces_hover_ibeam(cx: &mut TestAppContext) {
1875 cx.update(crate::init);
1876 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1877
1878 assert_eq!(TextView::new(&state).style.mouse_cursor, None);
1879 assert_eq!(
1880 TextView::new(&state).cursor_default().style.mouse_cursor,
1881 Some(CursorStyle::Arrow)
1882 );
1883
1884 state.update(cx, |state, _| {
1885 assert!(state.shows_text_cursor());
1886 state.hover_cursor = Some(CursorStyle::Arrow);
1887 assert!(!state.shows_text_cursor());
1888 state.is_selecting = true;
1889 assert!(state.shows_text_cursor());
1890 });
1891 }
1892
1893 #[gpui::test]
1894 fn stateless_markdown_with_rebuilt_parser_settles(cx: &mut TestAppContext) {
1895 cx.update(crate::init);
1896 let renders = Arc::new(AtomicUsize::new(0));
1897 let (_, cx) = cx.add_window_view({
1898 let renders = renders.clone();
1899 move |_, _| StatelessMarkdownRoot { renders }
1900 });
1901 let cx: &mut VisualTestContext = cx;
1902
1903 cx.run_until_parked();
1904 cx.update(|window, cx| window.draw(cx).clear(cx));
1905 let renders_after_redraw = renders.load(Ordering::Relaxed);
1906 cx.run_until_parked();
1907 assert_eq!(
1908 renders.load(Ordering::Relaxed),
1909 renders_after_redraw,
1910 "an unchanged TextView must not schedule another render after its parser is rebuilt",
1911 );
1912 }
1913
1914 #[gpui::test]
1915 fn markdown_data_url_image_is_decoded_inline(cx: &mut TestAppContext) {
1916 use gpui::{Image, ImageFormat, ImageSource};
1917
1918 const PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
1920
1921 cx.update(crate::init);
1922 let markdown = format!("Inline  image");
1923 let (_, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new(&markdown, cx));
1924 let cx: &mut VisualTestContext = cx;
1925
1926 cx.run_until_parked();
1927 cx.update(|window, cx| window.draw(cx).clear(cx));
1928
1929 let bytes = data_url::DataUrl::process(&format!("data:image/png;base64,{PNG_BASE64}"))
1934 .unwrap()
1935 .decode_to_vec()
1936 .unwrap()
1937 .0;
1938 let image = Arc::new(Image::from_bytes(ImageFormat::Png, bytes));
1939 assert!(
1940 cx.update(|_, cx| ImageSource::Image(image).is_asset_cached(cx)),
1941 "the data URL image must be handed to GPUI as decoded bytes",
1942 );
1943 }
1944
1945 #[gpui::test]
1946 fn unstyled_text_view_uses_base_tokens_for_link_and_input_selection(cx: &mut TestAppContext) {
1947 cx.update(crate::init);
1948 cx.update(|cx| {
1949 let colors = &mut crate::Theme::global_mut(cx).tokens.colors;
1950 colors.primary = gpui::rgb(0x55aaff).into();
1951 colors.selection = gpui::rgb(0x335577).into();
1952 });
1953 let (root, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new("[link](url)", cx));
1954 let cx: &mut VisualTestContext = cx;
1955
1956 cx.run_until_parked();
1957 root.read_with(cx, |root, cx| {
1958 let style = &root.text_view.read(cx).text_view_style;
1959 assert_eq!(style.link(), gpui::rgb(0x55aaff).into());
1960 assert_eq!(style.selection(), gpui::rgb(0x335577).into());
1961 });
1962 }
1963
1964 #[gpui::test]
1965 fn inline_code_view_refinement_keeps_unspecified_style_properties(cx: &mut TestAppContext) {
1966 use super::{TextViewDefaults, TextViewStyle};
1967 struct StyledCode(Entity<TextViewState>);
1968 impl Render for StyledCode {
1969 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1970 TextView::new(&self.0)
1971 .inline_code_style(
1972 StyleRefinement::default()
1973 .border_1()
1974 .border_color(gpui::blue()),
1975 )
1976 .into_any_element()
1977 }
1978 }
1979 cx.update(crate::init);
1980 cx.update(|cx| {
1981 cx.set_global(
1982 TextViewDefaults::default().with_style(
1983 TextViewStyle::default().with_inline_code_style(
1984 StyleRefinement::default()
1985 .text_size(rems(1.))
1986 .bg(gpui::red()),
1987 ),
1988 ),
1989 )
1990 });
1991 let (root, cx) = cx.add_window_view(|_, cx| {
1992 StyledCode(cx.new(|cx| TextViewState::markdown("before `code` after", cx)))
1993 });
1994 cx.run_until_parked();
1995 cx.update(|window, cx| window.draw(cx).clear(cx));
1996 root.read_with(cx, |root, cx| {
1997 let state = root.0.read(cx);
1998 let style = state.text_view_style.inline_code_style();
1999 assert_eq!(style.text.font_size, Some(rems(1.).into()));
2000 assert_eq!(style.background, Some(gpui::red().into()));
2001 assert_eq!(style.border_color, Some(gpui::blue()));
2002 assert_eq!(style.border_widths.left, Some(px(1.).into()));
2003 });
2004 }
2005
2006 #[gpui::test]
2007 fn list_and_blockquote_view_refinements_keep_unspecified_style_properties(
2008 cx: &mut TestAppContext,
2009 ) {
2010 use super::{TextViewDefaults, TextViewStyle};
2011 struct StyledBlocks(Entity<TextViewState>);
2012 impl Render for StyledBlocks {
2013 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2014 TextView::new(&self.0)
2015 .list_style(StyleRefinement::default().text_color(gpui::blue()))
2016 .blockquote_style(StyleRefinement::default().border_color(gpui::blue()))
2017 .into_any_element()
2018 }
2019 }
2020 cx.update(crate::init);
2021 cx.update(|cx| {
2022 cx.set_global(
2023 TextViewDefaults::default().with_style(
2024 TextViewStyle::default()
2025 .with_list_style(
2026 StyleRefinement::default().font_weight(gpui::FontWeight::BOLD),
2027 )
2028 .with_blockquote_style(StyleRefinement::default().border_l_4()),
2029 ),
2030 )
2031 });
2032 let (root, cx) = cx.add_window_view(|_, cx| {
2033 StyledBlocks(cx.new(|cx| TextViewState::markdown("- item\n\n> quote", cx)))
2034 });
2035 cx.run_until_parked();
2036 cx.update(|window, cx| window.draw(cx).clear(cx));
2037 root.read_with(cx, |root, cx| {
2038 let style = &root.0.read(cx).text_view_style;
2039 let marker = style.list_style();
2040 assert_eq!(marker.text.color, Some(gpui::blue()));
2041 assert_eq!(marker.text.font_weight, Some(gpui::FontWeight::BOLD));
2042 let quote = style.blockquote_style();
2043 assert_eq!(quote.border_color, Some(gpui::blue()));
2044 assert_eq!(quote.border_widths.left, Some(px(4.).into()));
2045 });
2046 }
2047
2048 impl TextViewTestRoot {
2049 fn new(text: &str, cx: &mut Context<Self>) -> Self {
2050 let text = text.to_string();
2051 let text_view = cx.new(|cx| TextViewState::markdown(&text, cx));
2052 Self { text_view }
2053 }
2054 }
2055
2056 impl Render for TextViewTestRoot {
2057 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2058 div()
2059 .w(px(160.))
2060 .child(
2061 div()
2062 .h(px(24.))
2063 .overflow_hidden()
2064 .child(TextView::new(&self.text_view).selectable(true)),
2065 )
2066 .child(div().h(px(40.)).child("footer"))
2067 }
2068 }
2069
2070 struct TableSelectionTestRoot {
2071 text_view: Entity<TextViewState>,
2072 }
2073
2074 impl Render for TableSelectionTestRoot {
2075 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2076 div()
2077 .debug_selector(|| "table-selection-root".into())
2078 .w(px(520.))
2079 .child(crate::TextSelectionLayer)
2080 .child(TextView::new(&self.text_view))
2081 }
2082 }
2083
2084 #[gpui::test]
2085 fn table_drag_selection_settles_without_requesting_idle_frames(cx: &mut TestAppContext) {
2086 cx.update(crate::init);
2087 let (_, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
2088 text_view: cx.new(|cx| {
2089 TextViewState::markdown(
2090 "| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
2091 cx,
2092 )
2093 }),
2094 });
2095 let cx: &mut VisualTestContext = cx;
2096
2097 cx.run_until_parked();
2098 let bounds = cx
2099 .debug_bounds("table-selection-root")
2100 .expect("table bounds");
2101 let start = point(bounds.left() + px(24.), bounds.top() + px(16.));
2102 let end = point(bounds.right() - px(24.), bounds.bottom() - px(16.));
2103 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2104 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2105 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2106
2107 assert!(cx.update(|window, cx| crate::TextSelection::has_selection(window, cx)));
2108 assert_eq!(
2109 cx.update(|window, cx| window.simulate_next_frame(cx)),
2110 0,
2111 "finished table selection must not continuously request frames"
2112 );
2113 }
2114
2115 #[gpui::test]
2119 fn table_drag_from_a_cell_stays_in_that_cell(cx: &mut TestAppContext) {
2120 cx.update(crate::init);
2121 let (root, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
2122 text_view: cx.new(|cx| {
2123 TextViewState::markdown(
2124 "Intro\n\n| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
2125 cx,
2126 )
2127 }),
2128 });
2129 let cx: &mut VisualTestContext = cx;
2130 cx.run_until_parked();
2131 cx.update(|window, cx| window.draw(cx).clear(cx));
2132
2133 let text_bounds = root.read_with(cx, |root, cx| {
2134 root.text_view.read(cx).selection_adapter.text_bounds()
2135 });
2136 assert_eq!(text_bounds.len(), 7, "{text_bounds:?}");
2137 let [intro, _, _, cell_a, cell_b, _, cell_d] = text_bounds[..] else {
2138 unreachable!()
2139 };
2140 let table = cx
2141 .debug_bounds("table-selection-root")
2142 .expect("table bounds");
2143 let start_of = |bounds: Bounds<Pixels>| point(bounds.left() + px(0.1), bounds.center().y);
2144 let end_of = |bounds: Bounds<Pixels>| point(bounds.right() - px(0.1), bounds.center().y);
2145
2146 let mut drag = |start, end| {
2147 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2148 cx.update(|window, cx| window.draw(cx).clear(cx));
2149 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2150 cx.update(|window, cx| window.draw(cx).clear(cx));
2151 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2152 cx.update(|window, cx| window.draw(cx).clear(cx));
2153 let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2154 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2155 (selected.trim().to_string(), copied.trim().to_string())
2156 };
2157
2158 let below = point(table.right() - px(2.), table.bottom() - px(1.));
2160 let expected = ("Cell A".to_string(), "Cell A".to_string());
2161 assert_eq!(drag(start_of(cell_a), below), expected);
2162
2163 let expected = ("Cell B".to_string(), "Cell B".to_string());
2166 let left = point(cell_a.center().x, cell_b.center().y);
2167 assert_eq!(drag(end_of(cell_b), left), expected);
2168 let above = point(table.left() + px(2.), intro.top());
2169 assert_eq!(drag(end_of(cell_b), above), expected);
2170
2171 let (selected, copied) = drag(start_of(intro), end_of(cell_d));
2173 for text in ["Intro", "Header 1", "Cell A", "Cell B", "Cell C", "Cell D"] {
2174 assert!(selected.contains(text), "{text} not in {selected:?}");
2175 assert!(copied.contains(text), "{text} not in {copied:?}");
2176 }
2177
2178 cx.simulate_mouse_down(start_of(cell_a), MouseButton::Left, Modifiers::default());
2181 cx.update(|window, cx| window.draw(cx).clear(cx));
2182 cx.simulate_mouse_move(end_of(cell_a), MouseButton::Left, Modifiers::default());
2183 cx.update(|window, cx| window.draw(cx).clear(cx));
2184 cx.simulate_mouse_move(below, MouseButton::Left, Modifiers::default());
2185 cx.simulate_mouse_up(below, MouseButton::Left, Modifiers::default());
2186 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2187 assert_eq!(copied.trim(), "Cell A");
2188 }
2189
2190 #[gpui::test]
2193 fn table_drag_selects_aligned_cell_text_where_it_is_painted(cx: &mut TestAppContext) {
2194 const SELECTION: u32 = 0xf020b0;
2195
2196 struct AlignedTableRoot {
2197 text_view: Entity<TextViewState>,
2198 }
2199
2200 impl Render for AlignedTableRoot {
2201 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2202 div()
2205 .w(px(520.))
2206 .underline()
2207 .child(crate::TextSelectionLayer)
2208 .child(TextView::new(&self.text_view).style(
2209 TextViewStyle::default().with_selection(gpui::rgb(SELECTION).into()),
2210 ))
2211 }
2212 }
2213
2214 cx.update(crate::init);
2215 let (root, cx) = cx.add_window_view(|_, cx| AlignedTableRoot {
2216 text_view: cx.new(|cx| {
2217 TextViewState::markdown(
2218 "| Quarterly revenue | Review status |\n| ---: | :---: |\n| 42 | ok |",
2219 cx,
2220 )
2221 }),
2222 });
2223 let cx: &mut VisualTestContext = cx;
2224 cx.run_until_parked();
2225 cx.update(|window, cx| window.draw(cx).clear(cx));
2226
2227 let mut underlines = cx.update(|window, _| {
2228 let scale_factor = window.scale_factor();
2229 window
2230 .painted_underlines()
2231 .into_iter()
2232 .map(|underline| underline.bounds.map(|value| px(value.0 / scale_factor)))
2233 .collect::<Vec<_>>()
2234 });
2235 underlines.sort_by(|a, b| {
2236 (a.top(), a.left())
2237 .partial_cmp(&(b.top(), b.left()))
2238 .expect("finite bounds")
2239 });
2240 let [right_head, center_head, right, center] = underlines[..] else {
2241 panic!("expected one underline per cell, got {underlines:?}");
2242 };
2243 assert!((right.right() - right_head.right()).abs() < px(1.));
2246 assert!(right.left() > right_head.left() + px(1.));
2247 assert!((center.center().x - center_head.center().x).abs() < px(1.));
2248 assert!(center.left() > center_head.left() + px(1.));
2249
2250 for (underline, expected) in [(right, "42"), (center, "ok")] {
2251 let y = underline.top() - px(4.);
2253 let start = point(underline.left() + px(0.1), y);
2254 let end = point(underline.right() - px(0.1), y);
2255 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2256 cx.update(|window, cx| window.draw(cx).clear(cx));
2257 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2258 cx.update(|window, cx| window.draw(cx).clear(cx));
2259 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2260 cx.update(|window, cx| window.draw(cx).clear(cx));
2261
2262 let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2263 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2264 assert_eq!(selected.trim(), expected);
2265 assert_eq!(copied.trim(), expected);
2266 let highlights = cx.update(|window, _| {
2267 let selection: gpui::Background = gpui::rgb(SELECTION).into();
2268 let scale_factor = window.scale_factor();
2269 window
2270 .painted_quads()
2271 .into_iter()
2272 .filter(|quad| quad.background == selection)
2273 .map(|quad| quad.bounds.map(|value| px(value.0 / scale_factor)))
2274 .collect::<Vec<_>>()
2275 });
2276 assert!(
2277 highlights.iter().any(|highlight| {
2278 highlight.left() <= underline.left() + px(1.)
2279 && highlight.right() >= underline.right() - px(1.)
2280 && highlight.top() <= y
2281 && highlight.bottom() >= underline.bottom()
2282 }),
2283 "the highlight {highlights:?} must cover the text above {underline:?}"
2284 );
2285 }
2286 }
2287
2288 struct CellSelectionTestRoot {
2289 text_view: Entity<TextViewState>,
2290 scrollable: bool,
2291 }
2292
2293 impl Render for CellSelectionTestRoot {
2294 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2295 div()
2296 .w(px(520.))
2297 .h(px(400.))
2298 .child(crate::TextSelectionLayer)
2299 .child(TextView::new(&self.text_view).scrollable(self.scrollable))
2300 }
2301 }
2302
2303 #[gpui::test]
2304 fn table_cell_copy_excludes_following_blocks_in_a_scrollable_view(cx: &mut TestAppContext) {
2305 cx.update(crate::init);
2306 let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2307 text_view: cx.new(|cx| TextViewState::markdown(
2308 "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |\n\nMiddle paragraph\n\nLast paragraph", cx)),
2309 scrollable: true,
2310 });
2311 cx.run_until_parked();
2312 cx.update(|window, cx| window.draw(cx).clear(cx));
2313 let rows = root.read_with(cx, |root, cx| {
2314 root.text_view.read(cx).selection_adapter.text_bounds()
2315 });
2316 assert_eq!(rows.len(), 6, "{rows:?}");
2317 let start = point(rows[2].left() + px(0.1), rows[2].center().y);
2318 let inside = point(rows[2].right() - px(0.1), rows[2].center().y);
2319 let end = point(rows[5].right() - px(0.1), rows[5].center().y);
2320 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2321 cx.simulate_mouse_move(inside, MouseButton::Left, Modifiers::default());
2322 cx.update(|window, cx| window.draw(cx).clear(cx));
2323 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2325 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2326 for format in [SelectionFormat::Plain, SelectionFormat::Source] {
2327 root.update(cx, |root, cx| {
2328 root.text_view
2329 .update(cx, |state, cx| state.set_selection_format(format, cx))
2330 });
2331 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2332 assert_eq!(copied.trim(), "Cell A", "{format:?}");
2333 }
2334 cx.update(|window, cx| window.draw(cx).clear(cx));
2335 let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2336 assert_eq!(selected.trim(), "Cell A");
2337 }
2338
2339 #[gpui::test]
2340 fn table_cell_touch_select_all_includes_every_cell(cx: &mut TestAppContext) {
2341 cx.update(crate::init);
2342 let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2343 text_view: cx.new(|cx| {
2344 TextViewState::markdown(
2345 "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
2346 cx,
2347 )
2348 }),
2349 scrollable: false,
2350 });
2351 cx.run_until_parked();
2352 cx.update(|window, cx| window.draw(cx).clear(cx));
2353 let rows = root.read_with(cx, |root, cx| {
2354 root.text_view.read(cx).selection_adapter.text_bounds()
2355 });
2356 let position = rows[2].center();
2357 for phase in [gpui::TouchPhase::Started, gpui::TouchPhase::Ended] {
2358 cx.simulate_event(gpui::LongPressEvent {
2359 phase,
2360 start_position: position,
2361 position,
2362 });
2363 }
2364 cx.update(|window, cx| {
2365 window.draw(cx).clear(cx);
2366 crate::TextSelection::select_all(window, cx);
2367 window.draw(cx).clear(cx);
2368 });
2369 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2370 let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2371 for text in ["Header", "Other", "Cell A", "Cell B"] {
2372 assert!(selected.contains(text), "{selected:?}");
2373 assert!(copied.contains(text), "{copied:?}");
2374 }
2375 }
2376
2377 #[gpui::test]
2378 fn table_cell_selection_does_not_leak_into_another_window(cx: &mut TestAppContext) {
2379 cx.update(crate::init);
2380 let start = {
2381 let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2382 text_view: cx.new(|cx| {
2383 TextViewState::markdown(
2384 "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
2385 cx,
2386 )
2387 }),
2388 scrollable: false,
2389 });
2390 cx.run_until_parked();
2391 cx.update(|window, cx| window.draw(cx).clear(cx));
2392 let rows = root.read_with(cx, |root, cx| {
2393 root.text_view.read(cx).selection_adapter.text_bounds()
2394 });
2395 let start = point(rows[0].left() + px(0.1), rows[0].center().y);
2396 let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2397 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2398 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2399 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2400 cx.update(|window, cx| window.draw(cx).clear(cx));
2401 assert_eq!(
2402 cx.update(|window, cx| crate::TextSelection::selected_text(window, cx))
2403 .trim(),
2404 "Header"
2405 );
2406 start
2407 };
2408 let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2409 text_view: cx.new(|cx| TextViewState::markdown("ordinary text in another window", cx)),
2410 scrollable: false,
2411 });
2412 cx.run_until_parked();
2413 cx.update(|window, cx| window.draw(cx).clear(cx));
2414 let rows = root.read_with(cx, |root, cx| {
2415 root.text_view.read(cx).selection_adapter.text_bounds()
2416 });
2417 assert!(rows[0].contains(&start), "{start:?}, {rows:?}");
2418 let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2419 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2420 cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2421 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2422 cx.update(|window, cx| window.draw(cx).clear(cx));
2423 let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2424 let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2425 assert!(!selected.trim().is_empty());
2426 assert_eq!(copied, selected);
2427 }
2428
2429 struct InlineImageTextViewTestRoot {
2430 text_view: Entity<TextViewState>,
2431 }
2432
2433 impl InlineImageTextViewTestRoot {
2434 fn new(cx: &mut Context<Self>) -> Self {
2435 let text_view = cx.new(|cx| {
2436 TextViewState::markdown(
2437 "Build Status  after",
2438 cx,
2439 )
2440 });
2441 Self { text_view }
2442 }
2443 }
2444
2445 impl Render for InlineImageTextViewTestRoot {
2446 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2447 div()
2448 .w(px(420.))
2449 .child(TextView::new(&self.text_view).selectable(true))
2450 }
2451 }
2452
2453 #[gpui::test]
2454 fn inline_image_keeps_surrounding_text_on_same_line(cx: &mut TestAppContext) {
2455 cx.update(crate::init);
2456 let (content, cx) = cx.add_window_view(|_, cx| InlineImageTextViewTestRoot::new(cx));
2457 let cx: &mut VisualTestContext = cx;
2458
2459 cx.run_until_parked();
2460 cx.update(|window, cx| {
2461 let _ = window.draw(cx);
2462 });
2463
2464 let inline_bounds = content.read_with(cx, |content, cx| {
2465 content.text_view.read(cx).selection_adapter.text_bounds()
2466 });
2467
2468 assert_eq!(inline_bounds.len(), 2);
2469 assert_eq!(
2470 inline_bounds[0].top(),
2471 inline_bounds[1].top(),
2472 "text before and after an inline image should share a rendered line"
2473 );
2474 assert!(
2475 inline_bounds[1].left() - inline_bounds[0].right() > px(8.),
2476 "inline image should reserve horizontal space in the text layout"
2477 );
2478 assert!(
2479 inline_bounds[1].left() - inline_bounds[0].right() < px(40.),
2480 "unloaded inline image fallback should stay generic and compact"
2481 );
2482 }
2483
2484 struct ImageSourceTestRoot {
2485 text_view: Entity<TextViewState>,
2486 image_source: Arc<dyn Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync>,
2487 }
2488
2489 impl ImageSourceTestRoot {
2490 fn new(
2491 markdown: &str,
2492 image_source: Arc<dyn Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync>,
2493 cx: &mut Context<Self>,
2494 ) -> Self {
2495 Self {
2496 text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
2497 image_source,
2498 }
2499 }
2500 }
2501
2502 impl Render for ImageSourceTestRoot {
2503 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2504 let image_source = self.image_source.clone();
2505 div().w(px(420.)).child(
2506 TextView::new(&self.text_view)
2507 .selectable(true)
2508 .image_source(move |uri| image_source(uri)),
2509 )
2510 }
2511 }
2512
2513 #[gpui::test]
2520 fn inline_image_without_size_is_drawn_at_its_intrinsic_size(cx: &mut TestAppContext) {
2521 use crate::test_support::sized_image_source;
2522
2523 cx.update(crate::init);
2524 let image_source = Arc::new(sized_image_source(200, 60));
2525 let (content, cx) = cx.add_window_view(|_, cx| {
2526 ImageSourceTestRoot::new("Before  after", image_source, cx)
2527 });
2528 let cx: &mut VisualTestContext = cx;
2529
2530 cx.run_until_parked();
2531 cx.update(|window, cx| window.draw(cx).clear(cx));
2532
2533 let inline_bounds = content.read_with(cx, |content, cx| {
2534 content.text_view.read(cx).selection_adapter.text_bounds()
2535 });
2536 assert_eq!(inline_bounds.len(), 2);
2537 assert_eq!(
2538 inline_bounds[0].top(),
2539 inline_bounds[1].top(),
2540 "text before and after the image share its line"
2541 );
2542 let gap = inline_bounds[1].left() - inline_bounds[0].right();
2543 assert!(
2544 gap > px(180.),
2545 "the image reserves its intrinsic width, not a line-height placeholder; gap {gap:?}"
2546 );
2547 }
2548
2549 #[gpui::test]
2552 fn inline_image_wider_than_the_view_wraps_the_text_after_it(cx: &mut TestAppContext) {
2553 use crate::test_support::sized_image_source;
2554
2555 cx.update(crate::init);
2556 let image_source = Arc::new(sized_image_source(600, 60));
2557 let (content, cx) = cx.add_window_view(|_, cx| {
2558 ImageSourceTestRoot::new("Before  after", image_source, cx)
2559 });
2560 let cx: &mut VisualTestContext = cx;
2561
2562 cx.run_until_parked();
2563 cx.update(|window, cx| window.draw(cx).clear(cx));
2564
2565 let inline_bounds = content.read_with(cx, |content, cx| {
2566 content.text_view.read(cx).selection_adapter.text_bounds()
2567 });
2568 assert_eq!(inline_bounds.len(), 2);
2569 assert!(
2570 inline_bounds[1].top() > inline_bounds[0].top(),
2571 "text after an image wider than the view wraps to the next line"
2572 );
2573 }
2574
2575 #[gpui::test]
2576 fn inline_html_image_after_newline_does_not_panic(cx: &mut TestAppContext) {
2577 cx.update(crate::init);
2578 let (_, cx) = cx.add_window_view(|_, cx| {
2579 TextViewTestRoot::new(
2580 "Hi\n[<img src=\"https://example.com/image.svg\">](https://google.com/)",
2581 cx,
2582 )
2583 });
2584 let cx: &mut VisualTestContext = cx;
2585
2586 cx.run_until_parked();
2587 cx.update(|window, cx| {
2588 let _ = window.draw(cx);
2589 });
2590 }
2591
2592 struct FittedListTestRoot {
2593 text_view: Entity<TextViewState>,
2594 width: Pixels,
2595 }
2596
2597 impl Render for FittedListTestRoot {
2598 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2599 div()
2600 .w(self.width)
2601 .flex()
2602 .flex_col()
2603 .items_end()
2604 .text_size(px(16.))
2605 .child(crate::TextSelectionLayer)
2606 .child(
2607 div()
2608 .debug_selector(|| "fitted-list".into())
2609 .flex()
2610 .flex_col()
2611 .min_w_0()
2612 .max_w_full()
2613 .p_4()
2614 .child(TextView::new(&self.text_view).selectable(true)),
2615 )
2616 }
2617 }
2618
2619 fn fitted_list_bounds(
2620 source: &str,
2621 width: f32,
2622 cx: &mut TestAppContext,
2623 ) -> (Bounds<Pixels>, Vec<Bounds<Pixels>>) {
2624 let (root, cx) = cx.add_window_view(|_, cx| FittedListTestRoot {
2625 text_view: cx.new(|cx| TextViewState::markdown(source, cx)),
2626 width: px(width),
2627 });
2628 cx.run_until_parked();
2629 cx.update(|window, cx| window.draw(cx).clear(cx));
2630 let bubble = cx.debug_bounds("fitted-list").unwrap();
2631 let rows = root.read_with(cx, |root, cx| {
2632 root.text_view.read(cx).selection_adapter.text_bounds()
2633 });
2634 assert!(!rows.is_empty(), "list text must be painted: {source:?}");
2635 for row in &rows {
2636 assert!(
2637 row.left() >= bubble.left() && row.right() <= bubble.right(),
2638 "text must remain visible inside the fitted container: {source:?}, {bubble:?}, {row:?}"
2639 );
2640 }
2641 (bubble, rows)
2642 }
2643
2644 #[gpui::test]
2645 fn fitted_lists_include_their_body_width(cx: &mut TestAppContext) {
2646 cx.update(crate::init);
2647 let (plain, _) = fitted_list_bounds("Hello world", 600., cx);
2648 for source in [
2649 "3. Hello world",
2650 "- Hello world",
2651 "- [ ] Hello world",
2652 "- [x] Hello world",
2653 "Intro\n\n- Hello world",
2654 "- Outer\n - Hello world",
2655 ] {
2656 let (bubble, _) = fitted_list_bounds(source, 600., cx);
2657 assert!(
2658 bubble.size.width > plain.size.width,
2659 "the marker must leave room for the full body: {source:?}, {bubble:?}, {plain:?}"
2660 );
2661 }
2662 }
2663
2664 #[gpui::test]
2665 fn fitted_lists_wrap_their_body_within_the_available_width(cx: &mut TestAppContext) {
2666 cx.update(crate::init);
2667 let body = "Visible text that wraps without being clipped. ".repeat(12);
2668 for width in [600., 180.] {
2669 for prefix in ["3. ", "- ", "- [ ] ", "- [x] ", "- Outer\n - "] {
2670 let (bubble, rows) = fitted_list_bounds(&format!("{prefix}{body}"), width, cx);
2671 assert!(bubble.size.width <= px(width));
2672 assert!(rows.len() > 1, "the body must wrap: {prefix:?}, {width}");
2673 }
2674 }
2675 }
2676
2677 #[gpui::test]
2678 fn list_item_renders_fenced_code_block_at_document_width(cx: &mut TestAppContext) {
2679 struct ListItemBlockRoot;
2680
2681 impl Render for ListItemBlockRoot {
2682 fn render(
2683 &mut self,
2684 _window: &mut Window,
2685 _cx: &mut Context<Self>,
2686 ) -> impl IntoElement {
2687 div().w(px(840.)).h(px(400.)).child(
2688 crate::h_resizable("markdown-width-test")
2689 .child(crate::resizable_panel().child(div()))
2690 .child(crate::resizable_panel().child(
2691 TextView::markdown(
2692 "list-with-code",
2693 "1. List item\n ```rust\n nested code\n ```\n\n```rust\ntop-level code\n```",
2694 )
2695 .code_block_actions(|code_block, _, _| {
2696 let selector = if code_block.code().contains("nested") {
2697 "nested-code-action"
2698 } else {
2699 "top-level-code-action"
2700 };
2701 div()
2702 .debug_selector(move || selector.into())
2703 .child("Copy")
2704 })
2705 .scrollable(true)
2706 .p_5()
2707 .flex_none(),
2708 )),
2709 )
2710 }
2711 }
2712
2713 cx.update(crate::init);
2714 let (_, cx) = cx.add_window_view(|_, _| ListItemBlockRoot);
2715 let cx: &mut VisualTestContext = cx;
2716
2717 cx.run_until_parked();
2718 cx.update(|window, cx| {
2719 let _ = window.draw(cx);
2720 });
2721
2722 let nested_action = cx.debug_bounds("nested-code-action").unwrap();
2723 let top_level_action = cx.debug_bounds("top-level-code-action").unwrap();
2724 assert!(
2725 top_level_action.right() - nested_action.right() < px(32.),
2726 "nested code block should fill the list item's available width"
2727 );
2728 }
2729
2730 const CODE_HEIGHT: Pixels = px(60.);
2732
2733 struct ScrollingCodeRoot {
2734 text_view: Entity<TextViewState>,
2735 actions: bool,
2736 }
2737
2738 impl Render for ScrollingCodeRoot {
2739 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2740 let mut code_block = StyleRefinement::default().max_h(CODE_HEIGHT);
2741 code_block.overflow.y = Some(Overflow::Scroll);
2742
2743 div().w(px(320.)).h(px(200.)).child(
2744 TextView::new(&self.text_view)
2745 .style(TextViewStyle::default().with_code_block(code_block))
2746 .when(self.actions, |this| {
2747 this.code_block_actions(|_, _, _| {
2748 div().debug_selector(|| "code-action".into()).child("Copy")
2749 })
2750 })
2751 .scrollable(true),
2752 )
2753 }
2754 }
2755
2756 #[gpui::test]
2757 fn scrolling_code_block_keeps_wheel_from_the_list(cx: &mut TestAppContext) {
2758 cx.update(crate::init);
2759 let code = (0..50).map(|i| format!("line {i}\n")).collect::<String>();
2760 let tail = "Paragraph after the code.\n\n".repeat(20);
2761 let markdown = format!("```\n{code}```\n\n{tail}");
2762
2763 for actions in [false, true] {
2766 let (root, cx) = cx.add_window_view(|_, cx| ScrollingCodeRoot {
2767 text_view: cx.new(|cx| TextViewState::markdown(&markdown, cx)),
2768 actions,
2769 });
2770 let cx: &mut VisualTestContext = cx;
2771 let draw = |cx: &mut VisualTestContext| {
2772 cx.run_until_parked();
2773 cx.update(|window, cx| window.draw(cx).clear(cx));
2774 };
2775 let step = px(20.);
2776 let wheel_at = |cx: &mut VisualTestContext, y: Pixels| {
2777 cx.simulate_event(gpui::ScrollEvent {
2778 position: point(px(20.), y),
2779 delta: gpui::ScrollDelta::Pixels(point(px(0.), -step)),
2780 ..Default::default()
2781 });
2782 };
2783 let edges = |cx: &mut VisualTestContext| {
2787 let lines = root.read_with(cx, |root, cx| {
2788 root.text_view.read(cx).selection_adapter.text_bounds()
2789 });
2790 let paragraph = lines.iter().find(|line| line.top() >= CODE_HEIGHT).unwrap();
2791 (lines[0].bottom(), paragraph.top())
2792 };
2793 draw(cx);
2794 let (code_bottom, paragraph_top) = edges(cx);
2795 let action = cx.debug_bounds("code-action");
2796
2797 wheel_at(cx, CODE_HEIGHT / 2.);
2800 draw(cx);
2801 assert_eq!(
2802 edges(cx),
2803 (code_bottom - step, paragraph_top),
2804 "actions: {actions}"
2805 );
2806 assert_eq!(cx.debug_bounds("code-action"), action);
2807
2808 wheel_at(cx, CODE_HEIGHT * 2.5);
2812 draw(cx);
2813 assert_ne!(edges(cx).1, paragraph_top, "actions: {actions}");
2814 }
2815 }
2816
2817 fn draw_table_with_actions(
2821 cx: &mut TestAppContext,
2822 scroll: bool,
2823 ) -> (Bounds<Pixels>, TableData) {
2824 use std::sync::{Arc, Mutex};
2825
2826 struct TableRoot {
2827 scroll: bool,
2828 captured: Arc<Mutex<Vec<TableData>>>,
2829 }
2830
2831 impl Render for TableRoot {
2832 fn render(
2833 &mut self,
2834 _window: &mut Window,
2835 _cx: &mut Context<Self>,
2836 ) -> impl IntoElement {
2837 let captured = self.captured.clone();
2838 let mut table_style = StyleRefinement::default();
2839 if self.scroll {
2840 table_style.overflow.x = Some(Overflow::Scroll);
2841 }
2842
2843 div().w(px(320.)).child(
2844 TextView::markdown(
2845 "table-actions",
2846 "| Name | Age |\n|:--|--:|\n| Alice | 30 |\n| Bob | 41 |",
2847 )
2848 .style(TextViewStyle::default().with_table(table_style))
2849 .table_actions(move |table, _, _| {
2850 if let Ok(mut captured) = captured.lock() {
2851 captured.push(table.clone());
2852 }
2853 div().debug_selector(|| "table-action".into()).child("Copy")
2854 }),
2855 )
2856 }
2857 }
2858
2859 cx.update(crate::init);
2860 let captured = Arc::new(Mutex::new(Vec::new()));
2861 let (_, cx) = cx.add_window_view({
2862 let captured = captured.clone();
2863 move |_, _| TableRoot { scroll, captured }
2864 });
2865 let cx: &mut VisualTestContext = cx;
2866
2867 cx.run_until_parked();
2868 cx.update(|window, cx| {
2869 let _ = window.draw(cx);
2870 });
2871
2872 let bounds = cx
2873 .debug_bounds("table-action")
2874 .expect("table actions should be painted");
2875 let data = captured
2876 .lock()
2877 .expect("captured table data")
2878 .last()
2879 .cloned()
2880 .expect("table actions hook should receive the table");
2881
2882 (bounds, data)
2883 }
2884
2885 #[gpui::test]
2886 fn table_actions_render_below_the_table(cx: &mut TestAppContext) {
2887 for scroll in [false, true] {
2888 let (bounds, data) = draw_table_with_actions(cx, scroll);
2889
2890 assert!(
2892 bounds.top() > px(40.),
2893 "actions should sit below the table (scroll: {scroll}), got {:?}",
2894 bounds.top()
2895 );
2896 assert_eq!(data.headers, vec!["Name", "Age"]);
2897 assert_eq!(data.rows, vec![vec!["Alice", "30"], vec!["Bob", "41"]]);
2898 assert_eq!(
2899 data.markdown,
2900 "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n| Bob | 41 |"
2901 );
2902 assert_eq!(data.span, Some(0..52));
2903 }
2904 }
2905
2906 const TASK_LIST: &str =
2908 "- [ ] Open\n - [x] Nested\n* [X] Star\n+ [ ] Plus\n1. [x] One\n2) [ ] Two\n";
2909 const TASK_LABELS: [&str; 6] = ["Open", "Nested", "Star", "Plus", "One", "Two"];
2910
2911 type TaskToggles = Arc<std::sync::Mutex<Vec<TaskToggleEvent>>>;
2912
2913 struct TaskListTestRoot {
2914 text_view: Entity<TextViewState>,
2915 toggles: Option<TaskToggles>,
2916 container_clicks: Arc<AtomicUsize>,
2917 }
2918
2919 impl Render for TaskListTestRoot {
2920 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2921 let container_clicks = self.container_clicks.clone();
2922 div()
2923 .id("task-list-container")
2924 .w(px(300.))
2925 .text_size(px(16.))
2926 .on_click(move |_, _, _| {
2927 container_clicks.fetch_add(1, Ordering::Relaxed);
2928 })
2929 .child(crate::TextSelectionLayer)
2930 .child(TextView::new(&self.text_view).when_some(
2931 self.toggles.clone(),
2932 |this, toggles| {
2933 this.on_task_toggle(move |event, _, _| {
2934 toggles.lock().unwrap().push(event.clone());
2935 })
2936 },
2937 ))
2938 }
2939 }
2940
2941 fn click_task_list(toggles: Option<TaskToggles>, cx: &mut TestAppContext) -> usize {
2944 cx.update(crate::init);
2945 let container_clicks = Arc::new(AtomicUsize::new(0));
2946 let (root, cx) = cx.add_window_view({
2947 let container_clicks = container_clicks.clone();
2948 move |_, cx| TaskListTestRoot {
2949 text_view: cx.new(|cx| TextViewState::markdown(TASK_LIST, cx)),
2950 toggles,
2951 container_clicks,
2952 }
2953 });
2954 cx.run_until_parked();
2955 cx.update(|window, cx| window.draw(cx).clear(cx));
2956 let text = |label: &str, cx: &mut VisualTestContext| {
2957 root.read_with(cx, |root, cx| {
2958 root.text_view
2959 .read(cx)
2960 .selection_adapter
2961 .text_position(label, 0)
2962 })
2963 };
2964 for label in TASK_LABELS {
2965 let checkbox = text(label, cx) - point(px(16.), px(0.));
2967 cx.simulate_click(checkbox, Modifiers::default());
2968 cx.update(|window, cx| window.draw(cx).clear(cx));
2969 }
2970 let open = text("Open", cx);
2971 cx.simulate_click(open, Modifiers::default());
2972 container_clicks.load(Ordering::Relaxed)
2973 }
2974
2975 #[gpui::test]
2976 fn task_checkbox_click_reports_its_new_state_item_and_marker(cx: &mut TestAppContext) {
2977 let toggles = TaskToggles::default();
2978 let container_clicks = click_task_list(Some(toggles.clone()), cx);
2979
2980 let reported: Vec<_> = toggles
2981 .lock()
2982 .unwrap()
2983 .iter()
2984 .map(|event| (event.checked(), event.item_range(), event.marker_range()))
2985 .collect();
2986 let task = |checked, item: &str, marker: &str| {
2987 let item_start = TASK_LIST.find(item).unwrap();
2988 let marker_start = item_start + item.find(marker).unwrap();
2989 (
2990 checked,
2991 item_start..item_start + item.len(),
2992 marker_start..marker_start + marker.len(),
2993 )
2994 };
2995 assert_eq!(
2996 reported,
2997 vec![
2998 task(true, "- [ ] Open\n - [x] Nested", "[ ]"),
2999 task(false, "- [x] Nested", "[x]"),
3000 task(false, "* [X] Star", "[X]"),
3001 task(true, "+ [ ] Plus", "[ ]"),
3002 task(false, "1. [x] One", "[x]"),
3003 task(true, "2) [ ] Two", "[ ]"),
3004 ],
3005 "each checkbox reports the flipped state, its item with any nested \
3006 list and exactly its `[ ]` / `[x]`, and a click on the item text \
3007 toggles nothing",
3008 );
3009 assert_eq!(
3010 container_clicks, 1,
3011 "only the click on the text reaches the container"
3012 );
3013 }
3014
3015 #[gpui::test]
3016 fn task_checkboxes_without_a_handler_are_not_interactive(cx: &mut TestAppContext) {
3017 let container_clicks = click_task_list(None, cx);
3018
3019 assert_eq!(
3020 container_clicks,
3021 TASK_LABELS.len() + 1,
3022 "every click, including those on a checkbox, reaches the container"
3023 );
3024 }
3025
3026 #[test]
3027 fn plugin_accepts_text_view_plugins_beyond_markdown() {
3028 let view = TextView::markdown("plugin-test", "").plugin(DummyTextViewPlugin);
3029
3030 assert!(view.selectable);
3031 }
3032
3033 #[test]
3034 fn syntax_highlighting_is_opt_in() {
3035 let default_view = TextView::markdown("default-code", "```rust\nfn main() {}\n```");
3036 assert!(default_view.code_block_highlighter.is_none());
3037
3038 let view = default_view.code_block_highlighter(|block| {
3039 vec![(
3040 0..block.code().len(),
3041 gpui::HighlightStyle {
3042 color: Some(gpui::rgb(0x3366ff).into()),
3043 ..Default::default()
3044 },
3045 )]
3046 });
3047 assert!(view.code_block_highlighter.is_some());
3048 }
3049
3050 #[gpui::test]
3051 fn clipped_markdown_link_does_not_open(cx: &mut TestAppContext) {
3052 cx.update(crate::init);
3053 let (_, cx) = cx.add_window_view(|_, cx| {
3054 TextViewTestRoot::new("visible\n\n[hidden](https://example.com)", cx)
3055 });
3056 let cx: &mut VisualTestContext = cx;
3057
3058 cx.simulate_click(point(px(10.), px(34.)), Modifiers::default());
3059
3060 assert_eq!(cx.opened_url(), None);
3061 }
3062
3063 struct MaxLinesTestRoot {
3064 text_view: Entity<TextViewState>,
3065 max_lines: usize,
3066 }
3067
3068 impl MaxLinesTestRoot {
3069 fn new(text: &str, max_lines: usize, cx: &mut Context<Self>) -> Self {
3070 let text_view = cx.new(|cx| TextViewState::markdown(text, cx));
3071 Self {
3072 text_view,
3073 max_lines,
3074 }
3075 }
3076 }
3077
3078 impl Render for MaxLinesTestRoot {
3079 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3080 div()
3081 .w(px(200.))
3082 .child(TextView::new(&self.text_view).max_lines(self.max_lines))
3083 }
3084 }
3085
3086 #[test]
3087 fn the_clip_only_moves_for_a_straddling_glyph_line() {
3088 use super::line_safe_clip_bottom;
3089 use crate::text::state::LineSpan;
3090
3091 let spans = [
3092 LineSpan {
3094 top: px(0.),
3095 bottom: px(60.),
3096 line_height: px(20.),
3097 },
3098 LineSpan {
3100 top: px(68.),
3101 bottom: px(128.),
3102 line_height: px(20.),
3103 },
3104 ];
3105
3106 let below = px(400.);
3108
3109 assert_eq!(
3111 line_safe_clip_bottom(&spans, px(100.), below),
3112 Some(px(88.))
3113 );
3114
3115 assert_eq!(line_safe_clip_bottom(&spans, px(88.), below), None);
3117
3118 assert_eq!(line_safe_clip_bottom(&spans, px(64.), below), Some(px(60.)));
3121
3122 let one_block = [LineSpan {
3125 top: px(0.),
3126 bottom: px(60.),
3127 line_height: px(20.),
3128 }];
3129 assert_eq!(line_safe_clip_bottom(&one_block, px(200.), below), None);
3130
3131 assert_eq!(line_safe_clip_bottom(&spans, px(130.), px(128.)), None);
3134 }
3135
3136 #[test]
3137 fn a_line_taller_than_the_budget_keeps_the_part_that_fits() {
3138 use super::line_safe_clip_bottom;
3139 use crate::text::state::LineSpan;
3140
3141 let heading = [LineSpan {
3143 top: px(70.),
3144 bottom: px(98.),
3145 line_height: px(28.),
3146 }];
3147
3148 assert_eq!(line_safe_clip_bottom(&heading, px(96.), px(400.)), None);
3149 }
3150
3151 #[test]
3152 fn the_clip_does_not_stop_on_a_row_of_border_and_padding() {
3153 use super::line_safe_clip_bottom;
3154 use crate::text::state::LineSpan;
3155
3156 let rows = [
3159 LineSpan {
3160 top: px(100.),
3161 bottom: px(126.),
3162 line_height: px(26.),
3163 },
3164 LineSpan {
3165 top: px(135.),
3166 bottom: px(161.),
3167 line_height: px(26.),
3168 },
3169 ];
3170
3171 assert_eq!(
3174 line_safe_clip_bottom(&rows, px(148.), px(400.)),
3175 Some(px(126.))
3176 );
3177 }
3178
3179 struct ClampedPageRoot {
3185 text_view: Entity<TextViewState>,
3186 max_lines: usize,
3187 }
3188
3189 impl Render for ClampedPageRoot {
3190 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3191 use crate::{h_flex, v_flex};
3192
3193 v_flex()
3194 .size_full()
3195 .p_4()
3196 .gap_4()
3197 .child(h_flex().max_w(px(480.)).gap_3().child("header"))
3198 .child(
3199 v_flex()
3200 .flex_1()
3201 .min_h_0()
3202 .gap_4()
3203 .id("clamped-page-scroll")
3204 .child(
3205 v_flex()
3206 .max_w(px(480.))
3207 .p_3()
3208 .gap_2()
3209 .child(TextView::new(&self.text_view).max_lines(self.max_lines)),
3210 )
3211 .overflow_y_scroll(),
3212 )
3213 }
3214 }
3215
3216 #[gpui::test]
3217 fn max_lines_measures_overflow_inside_a_sized_page(cx: &mut TestAppContext) {
3218 cx.update(crate::init);
3219 let (root, cx) = cx.add_window_view(|_, cx| {
3220 let text_view = cx.new(|cx| {
3221 TextViewState::markdown(
3222 "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth\n\nseventh",
3223 cx,
3224 )
3225 });
3226 ClampedPageRoot {
3227 text_view,
3228 max_lines: 3,
3229 }
3230 });
3231 let cx: &mut VisualTestContext = cx;
3232
3233 assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3234 }
3235
3236 #[gpui::test]
3237 fn max_lines_clamps_overflowing_content(cx: &mut TestAppContext) {
3238 cx.update(crate::init);
3239 let (root, cx) = cx.add_window_view(|_, cx| {
3240 MaxLinesTestRoot::new(
3241 "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth",
3242 2,
3243 cx,
3244 )
3245 });
3246 let cx: &mut VisualTestContext = cx;
3247
3248 assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3249 }
3250
3251 #[gpui::test]
3252 fn max_lines_leaves_short_content_unclamped(cx: &mut TestAppContext) {
3253 cx.update(crate::init);
3254 let (root, cx) = cx.add_window_view(|_, cx| MaxLinesTestRoot::new("only line", 3, cx));
3255 let cx: &mut VisualTestContext = cx;
3256
3257 assert!(!root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3258 }
3259
3260 #[gpui::test]
3261 fn heading_refinement_changes_rendered_heading_geometry(cx: &mut TestAppContext) {
3262 struct HeadingStyleRoot;
3263
3264 impl Render for HeadingStyleRoot {
3265 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3266 div()
3267 .flex()
3268 .items_start()
3269 .child(
3270 div()
3271 .debug_selector(|| "default-h1".into())
3272 .child(TextView::markdown("default-h1-view", "# Heading")),
3273 )
3274 .child(div().debug_selector(|| "custom-h1".into()).child(
3275 TextView::markdown("custom-heading-view", "# Heading").style(
3276 TextViewStyle::default().with_heading(|level| {
3277 if level == 1 {
3278 StyleRefinement::default().pb(rems(2.))
3279 } else {
3280 StyleRefinement::default()
3281 }
3282 }),
3283 ),
3284 ))
3285 .child(
3286 div()
3287 .debug_selector(|| "default-h2".into())
3288 .child(TextView::markdown("default-h2-view", "## Heading")),
3289 )
3290 .child(div().debug_selector(|| "custom-h2".into()).child(
3291 TextView::markdown("custom-h2-view", "## Heading").style(
3292 TextViewStyle::default().with_heading(|level| {
3293 if level == 1 {
3294 StyleRefinement::default().pb(rems(2.))
3295 } else {
3296 StyleRefinement::default()
3297 }
3298 }),
3299 ),
3300 ))
3301 }
3302 }
3303
3304 cx.update(crate::init);
3305 let (_, cx) = cx.add_window_view(|_, _| HeadingStyleRoot);
3306 cx.update(|window, cx| window.draw(cx).clear(cx));
3307
3308 let default_h1 = cx.debug_bounds("default-h1").unwrap();
3309 let custom_h1 = cx.debug_bounds("custom-h1").unwrap();
3310 let default_h2 = cx.debug_bounds("default-h2").unwrap();
3311 let custom_h2 = cx.debug_bounds("custom-h2").unwrap();
3312 assert!(custom_h1.size.height > default_h1.size.height);
3313 assert_eq!(custom_h2.size.height, default_h2.size.height);
3314 }
3315
3316 #[gpui::test]
3317 fn max_lines_disables_links_hidden_by_the_clamp(cx: &mut TestAppContext) {
3318 cx.update(crate::init);
3319 let (_, cx) = cx.add_window_view(|_, cx| {
3320 MaxLinesTestRoot::new(
3321 "first\n\nsecond\n\nthird\n\n[hidden](https://example.com)",
3322 2,
3323 cx,
3324 )
3325 });
3326 let cx: &mut VisualTestContext = cx;
3327
3328 cx.simulate_click(point(px(10.), px(150.)), Modifiers::default());
3330
3331 assert_eq!(cx.opened_url(), None);
3332 }
3333
3334 #[gpui::test]
3335 fn scaled_inline_code_keeps_links_and_drag_selection(cx: &mut TestAppContext) {
3336 struct SelectionRoot {
3337 text_view: Entity<TextViewState>,
3338 format: crate::text::SelectionFormat,
3339 }
3340 impl Render for SelectionRoot {
3341 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3342 div()
3343 .w(px(160.))
3344 .child(crate::TextSelectionLayer)
3345 .child(TextView::new(&self.text_view).selection_format(self.format))
3346 }
3347 }
3348 cx.update(crate::init);
3349 let (view, cx) = cx.add_window_view(|_, cx| SelectionRoot {
3350 format: crate::text::SelectionFormat::Plain,
3351 text_view: cx
3352 .new(|cx| TextViewState::markdown("[`code`](https://example.com) after", cx)),
3353 });
3354 let cx: &mut VisualTestContext = cx;
3355 cx.run_until_parked();
3356 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
3357 assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
3358 cx.simulate_mouse_down(
3360 point(px(5.), px(8.)),
3361 MouseButton::Left,
3362 Modifiers::default(),
3363 );
3364 cx.update(|window, cx| {
3365 let _ = window.draw(cx);
3366 });
3367 cx.simulate_mouse_move(
3368 point(px(155.), px(20.)),
3369 Some(MouseButton::Left),
3370 Modifiers::default(),
3371 );
3372 cx.update(|window, cx| {
3373 let _ = window.draw(cx);
3374 });
3375 cx.simulate_mouse_up(
3376 point(px(155.), px(20.)),
3377 MouseButton::Left,
3378 Modifiers::default(),
3379 );
3380 cx.update(|window, cx| {
3381 let _ = window.draw(cx);
3382 });
3383 let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
3384 assert_eq!(selected.trim(), "code after");
3385 view.update(cx, |view, cx| {
3386 view.format = crate::text::SelectionFormat::Source;
3387 cx.notify();
3388 });
3389 cx.update(|window, cx| {
3390 let _ = window.draw(cx);
3391 });
3392 let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
3393 assert_eq!(selected.trim(), "[`code`](https://example.com) after");
3394 }
3395
3396 #[test]
3406 fn inline_code_heading_reserves_painted_wrapped_lines_and_list_baseline() {
3407 use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3408 use gpui::{TestApp, rems};
3409
3410 const MARKDOWN: &str = "The same words with inline code.\n\nThe same words with `inline code`.\n\n- The same words with inline code.\n- The same words with `inline code`.\n\n# Heading with inline code\n# Heading with `inline code`\n\nthis is a test";
3411
3412 struct MarkdownRoot {
3413 text_view: Entity<TextViewState>,
3414 width: Pixels,
3415 preview_zoom: f32,
3416 }
3417
3418 impl Render for MarkdownRoot {
3419 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3420 div()
3421 .w(self.width)
3422 .text_size(rems(self.preview_zoom))
3425 .child(crate::TextSelectionLayer)
3426 .child(TextView::new(&self.text_view).selectable(true))
3427 }
3428 }
3429
3430 fn draw(
3431 app: &mut TestApp,
3432 width: Pixels,
3433 preview_zoom: f32,
3434 ) -> (Bounds<Pixels>, Vec<Bounds<Pixels>>, String) {
3435 let mut window = app.open_window(|_, cx| MarkdownRoot {
3436 text_view: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
3437 width,
3438 preview_zoom,
3439 });
3440 window.draw();
3441 app.run_until_parked();
3442 window.draw();
3443 window.update(|root, _, cx| {
3444 root.text_view.update(cx, |state, cx| state.select_all(cx));
3445 });
3446 window.draw();
3447 window.read(|root, cx| {
3448 let state = root.text_view.read(cx);
3449 (
3450 state.bounds(),
3451 state.selection_adapter.text_bounds(),
3452 state.selected_text(),
3453 )
3454 })
3455 }
3456
3457 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3458 app.update(|cx| {
3459 crate::init(cx);
3460 crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3461 });
3462
3463 for (case, width, preview_zoom) in [
3464 ("default-16px", px(600.), 1.),
3467 ("narrow-16px", px(320.), 1.),
3469 ("zoom-1.25", px(600.), 1.25),
3471 ] {
3472 let (view_bounds, text_bounds, selected_text) = draw(&mut app, width, preview_zoom);
3473 assert!(
3474 text_bounds.len() > 8,
3475 "{case}: expected all markdown fragments"
3476 );
3477 assert_eq!(
3478 selected_text.trim(),
3479 "The same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nHeading with inline code\nHeading with inline code\nthis is a test",
3480 "{case}: wrapped inline-code text was lost or duplicated"
3481 );
3482 let following = text_bounds.last().expect("following paragraph must paint");
3483 let painted_bottom = text_bounds
3484 .iter()
3485 .map(|bounds| bounds.bottom())
3486 .max()
3487 .expect("markdown must paint text");
3488 assert!(
3494 text_bounds[..text_bounds.len() - 1]
3495 .iter()
3496 .all(|bounds| bounds.bottom() <= following.top()),
3497 "{case}: heading/list text painted through the following paragraph; following={following:?}, text_bounds={text_bounds:?}, view={view_bounds:?}"
3498 );
3499 assert!(
3500 painted_bottom <= view_bounds.bottom(),
3501 "{case}: TextView height did not reserve its painted text; painted_bottom={painted_bottom:?}, view={view_bounds:?}"
3502 );
3503 }
3504 }
3505
3506 #[test]
3507 fn ordered_markdown_list_start_reaches_layout_marker() {
3508 use crate::text::inline::test_fonts::{WideMonoTextSystem, record_shaped_lines};
3509 use gpui::TestApp;
3510
3511 struct MarkdownRoot {
3512 text_view: Entity<TextViewState>,
3513 }
3514
3515 impl Render for MarkdownRoot {
3516 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3517 div().w(px(400.)).child(TextView::new(&self.text_view))
3518 }
3519 }
3520
3521 #[derive(Clone, Copy)]
3522 enum Format {
3523 Markdown,
3524 Html,
3525 }
3526
3527 fn shaped_markers(format: Format, source: &str) -> Vec<String> {
3528 let (_, shaped_lines) = record_shaped_lines(|| {
3529 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3530 app.update(crate::init);
3531 let mut window = app.open_window(|_, cx| MarkdownRoot {
3532 text_view: cx.new(|cx| match format {
3533 Format::Markdown => TextViewState::markdown(source, cx),
3534 Format::Html => TextViewState::html(source, cx),
3535 }),
3536 });
3537 window.draw();
3538 app.run_until_parked();
3539 window.draw();
3540 });
3541
3542 let mut markers = shaped_lines
3543 .into_iter()
3544 .filter(|line| line.len() <= 3 && line.ends_with('.'))
3545 .collect::<Vec<_>>();
3546 markers.dedup();
3547 markers
3548 }
3549
3550 let starts_at_one = "1. one\n2. two";
3551 assert_eq!(
3552 shaped_markers(Format::Markdown, starts_at_one),
3553 ["1.", "2."]
3554 );
3555 assert_eq!(
3556 shaped_markers(Format::Html, "<ol><li>one</li><li>two</li></ol>"),
3557 ["1.", "2."]
3558 );
3559
3560 assert_eq!(
3561 shaped_markers(Format::Markdown, "3. hello\n4. world"),
3562 ["3.", "4."]
3563 );
3564
3565 let nested_starts_at_four = "1. outer\n\n 4. nested\n 5. again";
3566 assert_eq!(
3567 shaped_markers(Format::Markdown, nested_starts_at_four),
3568 ["1.", "D.", "E."]
3569 );
3570
3571 let nested_starts_at_zero = "1. outer\n\n 0. zero";
3572 assert_eq!(
3573 shaped_markers(Format::Markdown, nested_starts_at_zero),
3574 ["1.", "0."]
3575 );
3576 }
3577
3578 #[test]
3583 fn inline_code_line_is_as_tall_as_a_plain_line() {
3584 use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3585 use gpui::{TestApp, rems};
3586
3587 struct LineRoot {
3588 plain: Entity<TextViewState>,
3589 code: Entity<TextViewState>,
3590 preview_zoom: f32,
3591 }
3592
3593 impl Render for LineRoot {
3594 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3595 div()
3596 .w(px(600.))
3597 .text_size(rems(self.preview_zoom))
3598 .child(TextView::new(&self.plain))
3599 .child(TextView::new(&self.code))
3600 }
3601 }
3602
3603 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3604 app.update(|cx| {
3605 crate::init(cx);
3606 crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3607 });
3608 for scale_factor in [1.6, 2.] {
3609 for preview_zoom in [1., 1.25] {
3610 let mut window = app.open_window(|_, cx| LineRoot {
3611 plain: cx.new(|cx| TextViewState::markdown("plain body words", cx)),
3612 code: cx.new(|cx| TextViewState::markdown("plain `code` words", cx)),
3613 preview_zoom,
3614 });
3615 window.simulate_scale_factor_change(scale_factor);
3616 window.draw();
3617 app.run_until_parked();
3618 window.draw();
3619 let (plain, code) = window.read(|root, cx| {
3620 (
3621 root.plain.read(cx).bounds().size.height,
3622 root.code.read(cx).bounds().size.height,
3623 )
3624 });
3625 assert_eq!(code, plain, "scale {scale_factor}, zoom {preview_zoom}");
3626 }
3627 }
3628 }
3629
3630 #[test]
3634 fn inline_code_list_body_paint_origin_matches_plain_list_item() {
3635 use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3636 use gpui::{TestApp, rems};
3637
3638 struct ListRoot {
3639 plain: Entity<TextViewState>,
3640 code: Entity<TextViewState>,
3641 preview_zoom: f32,
3642 }
3643
3644 impl Render for ListRoot {
3645 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3646 div()
3647 .w(px(600.))
3648 .text_size(rems(self.preview_zoom))
3649 .child(crate::TextSelectionLayer)
3650 .child(TextView::new(&self.plain).selectable(true))
3651 .child(TextView::new(&self.code).selectable(true))
3652 }
3653 }
3654
3655 fn draw(app: &mut TestApp, preview_zoom: f32) -> (Pixels, Pixels) {
3656 let mut window = app.open_window(|_, cx| ListRoot {
3657 plain: cx.new(|cx| TextViewState::markdown("- plain body words", cx)),
3658 code: cx.new(|cx| TextViewState::markdown("- plain `code` words", cx)),
3659 preview_zoom,
3660 });
3661 window.draw();
3662 app.run_until_parked();
3663 window.draw();
3664 window.read(|root, cx| {
3665 let first_body_line_top = |view: &Entity<TextViewState>| {
3666 let view = view.read(cx);
3667 let painted_line = view
3668 .selection_adapter
3669 .text_bounds()
3670 .into_iter()
3671 .next()
3672 .expect("list item should paint its first body line");
3673 painted_line.top() - view.bounds().top()
3674 };
3675 (
3676 first_body_line_top(&root.plain),
3677 first_body_line_top(&root.code),
3678 )
3679 })
3680 }
3681
3682 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3683 app.update(|cx| {
3684 crate::init(cx);
3685 crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3686 });
3687 for (case, preview_zoom) in [("16px", 1.), ("zoom-1.25", 1.25), ("zoom-1.5", 1.5)] {
3688 let (plain_origin, code_origin) = draw(&mut app, preview_zoom);
3689 assert_eq!(
3690 code_origin, plain_origin,
3691 "{case}: code list body paint origin {code_origin:?} must match plain {plain_origin:?}"
3692 );
3693 }
3694 }
3695
3696 #[test]
3697 fn inline_code_fragment_does_not_paint_past_its_reserved_row() {
3698 use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3699 use gpui::TestApp;
3700
3701 const TEXT_BACKGROUND: u32 = 0x20f0b0;
3702
3703 struct MarkdownRoot {
3704 text_view: Entity<TextViewState>,
3705 }
3706
3707 impl Render for MarkdownRoot {
3708 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3709 div()
3710 .w(px(640.))
3711 .text_size(px(17.9))
3712 .text_bg(gpui::rgb(TEXT_BACKGROUND))
3713 .child(TextView::new(&self.text_view))
3714 }
3715 }
3716
3717 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3718 app.update(|cx| {
3719 crate::init(cx);
3720 crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3721 });
3722 let mut window = app.open_window(|_, cx| MarkdownRoot {
3723 text_view: cx.new(|cx| TextViewState::markdown("`main` starts the paragraph", cx)),
3724 });
3725 window.draw();
3726 app.run_until_parked();
3727 window.draw();
3728
3729 let (view_bounds, painted) = window.update(|root, window, cx| {
3730 let view_bounds = root
3731 .text_view
3732 .read(cx)
3733 .bounds()
3734 .scale(window.scale_factor());
3735 let text_background: gpui::Background = gpui::rgb(TEXT_BACKGROUND).into();
3736 let painted = window
3737 .painted_quads()
3738 .into_iter()
3739 .filter(|quad| quad.background == text_background)
3740 .map(|quad| quad.bounds)
3741 .collect::<Vec<_>>();
3742 (view_bounds, painted)
3743 });
3744
3745 assert!(
3746 !painted.is_empty(),
3747 "the inherited text background must make actual text paint observable"
3748 );
3749 assert!(
3750 painted
3751 .iter()
3752 .all(|bounds| bounds.bottom() <= view_bounds.bottom()),
3753 "an inline-code fragment wrapped a second time after InlineFlow reserved one row; \
3754 text background quads={painted:?}, reserved TextView bounds={view_bounds:?}"
3755 );
3756 }
3757
3758 #[test]
3759 fn table_row_backgrounds_follow_the_frame_corner_radius() {
3760 use gpui::TestApp;
3761
3762 const HEAD_BACKGROUND: u32 = 0x11aa77;
3763 const RADIUS: f32 = 8.;
3764
3765 struct RoundedTableRoot {
3766 text_view: Entity<TextViewState>,
3767 scroll: bool,
3768 }
3769
3770 impl Render for RoundedTableRoot {
3771 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3772 let mut table = StyleRefinement::default();
3773 table.corner_radii.top_left = Some(px(RADIUS).into());
3774 table.corner_radii.top_right = Some(px(RADIUS).into());
3775 table.corner_radii.bottom_left = Some(px(RADIUS).into());
3776 table.corner_radii.bottom_right = Some(px(RADIUS).into());
3777 if self.scroll {
3778 table.overflow.x = Some(gpui::Overflow::Scroll);
3779 }
3780 let style = TextViewStyle::default()
3781 .with_code_background(gpui::rgb(HEAD_BACKGROUND).into())
3782 .with_table(table);
3783 div()
3784 .w(px(400.))
3785 .child(TextView::new(&self.text_view).style(style))
3786 }
3787 }
3788
3789 for scroll in [false, true] {
3790 let mode = if scroll { "scroll" } else { "wrap" };
3791 let mut app = TestApp::new();
3792 app.update(crate::init);
3793 let mut window = app.open_window(|_, cx| RoundedTableRoot {
3794 text_view: cx
3795 .new(|cx| TextViewState::markdown("| a | b |\n| --- | --- |\n| 1 | 2 |", cx)),
3796 scroll,
3797 });
3798 window.draw();
3799 app.run_until_parked();
3800 window.draw();
3801
3802 let (quad, scale) = window.update(|_, window, _| {
3803 let head: gpui::Background = gpui::rgb(HEAD_BACKGROUND).into();
3804 let quad = window
3807 .painted_quads()
3808 .into_iter()
3809 .find(|quad| {
3810 quad.background == head && quad.corner_radii != Default::default()
3811 })
3812 .unwrap_or_else(|| panic!("{mode}: the header background quad is painted"));
3813 (quad, window.scale_factor())
3814 });
3815
3816 let expected = px(RADIUS - 1.).scale(scale);
3819 assert_eq!(quad.corner_radii.top_left, expected, "{mode}: top left");
3820 assert_eq!(quad.corner_radii.top_right, expected, "{mode}: top right");
3821 let square = px(0.).scale(scale);
3822 assert_eq!(quad.corner_radii.bottom_left, square, "{mode}: bottom left");
3823 assert_eq!(
3824 quad.corner_radii.bottom_right, square,
3825 "{mode}: bottom right"
3826 );
3827 }
3828 }
3829
3830 #[test]
3835 fn table_body_row_under_the_pointer_takes_the_hover_background() {
3836 use gpui::TestApp;
3837 use std::{cell::Cell, rc::Rc};
3838
3839 const HEAD_BACKGROUND: u32 = 0x11aa77;
3840 const ROW_HOVER: u32 = 0x7711aa;
3841
3842 struct HoverTableRoot {
3843 text_view: Entity<TextViewState>,
3844 scroll: bool,
3845 }
3846
3847 impl Render for HoverTableRoot {
3848 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3849 let mut table = StyleRefinement::default();
3850 if self.scroll {
3851 table.overflow.x = Some(Overflow::Scroll);
3852 }
3853 let style = TextViewStyle::default()
3854 .with_code_background(gpui::rgb(HEAD_BACKGROUND).into())
3855 .with_table(table)
3856 .with_table_row_hover(gpui::rgb(ROW_HOVER).into());
3857 div()
3858 .w(px(400.))
3859 .child(TextView::new(&self.text_view).style(style))
3860 }
3861 }
3862
3863 let table = "| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |";
3864 let source = format!("{table}\n\nBetween\n\n{table}");
3865 for scroll in [false, true] {
3866 let mode = if scroll { "scroll" } else { "wrap" };
3867 let mut app = TestApp::new();
3868 app.update(crate::init);
3869 let mut window = app.open_window(|_, cx| HoverTableRoot {
3870 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
3871 scroll,
3872 });
3873 window.draw();
3874 app.run_until_parked();
3875 window.draw();
3876
3877 let notifications = Rc::new(Cell::new(0));
3880 let text_view = window.update(|root, _, _| root.text_view.clone());
3881 app.update(|cx| {
3882 let notifications = notifications.clone();
3883 cx.observe(&text_view, move |_, _| {
3884 notifications.set(notifications.get() + 1)
3885 })
3886 .detach();
3887 });
3888
3889 let (heads, scale) = window.update(|_, window, _| {
3891 let scale = window.scale_factor();
3892 let head: gpui::Background = gpui::rgb(HEAD_BACKGROUND).into();
3893 let mut heads = window
3894 .painted_quads()
3895 .into_iter()
3896 .filter(|quad| quad.background == head)
3897 .map(|quad| quad.bounds.map(|value| px(value.as_f32() / scale)))
3898 .collect::<Vec<_>>();
3899 heads.sort_by_key(|bounds| bounds.origin.y);
3900 (heads, scale)
3901 });
3902 assert_eq!(heads.len(), 2, "{mode}: two header rows");
3903 let first_body_row =
3904 |head: Bounds<Pixels>| point(head.center().x, head.bottom() + px(4.));
3905 let first_head = heads[0].center();
3906 let first_row = first_body_row(heads[0]);
3907 let second_row = first_body_row(heads[1]);
3908 let outside = point(px(600.), first_row.y);
3909
3910 for (step, position, highlighted) in [
3911 ("first table's body row", first_row, true),
3912 ("first table's header", first_head, false),
3913 ("second table's body row", second_row, true),
3914 ("same row of the first table", first_row, true),
3915 ("outside the tables", outside, false),
3916 ] {
3917 let before = notifications.get();
3918 window.simulate_mouse_move(position);
3919 assert!(
3920 notifications.get() > before,
3921 "{mode}: moving onto the {step} notifies the view"
3922 );
3923 window.draw();
3924
3925 let hovered = window.update(|_, window, _| {
3926 let hover: gpui::Background = gpui::rgb(ROW_HOVER).into();
3927 window
3928 .painted_quads()
3929 .into_iter()
3930 .filter(|quad| quad.background == hover)
3931 .map(|quad| quad.bounds)
3932 .collect::<Vec<_>>()
3933 });
3934 if highlighted {
3935 assert_eq!(
3936 hovered.len(),
3937 1,
3938 "{mode}: one row is highlighted on the {step}"
3939 );
3940 assert!(
3941 hovered[0].contains(&position.scale(scale)),
3942 "{mode}: the {step} is highlighted, not {:?}",
3943 hovered[0]
3944 );
3945 } else {
3946 assert!(
3947 hovered.is_empty(),
3948 "{mode}: nothing is highlighted on the {step}"
3949 );
3950 }
3951 }
3952 }
3953 }
3954
3955 #[test]
3961 fn table_keeps_narrow_columns_on_one_line_while_wide_ones_wrap() {
3962 use crate::text::inline::test_fonts::WideMonoTextSystem;
3963 use gpui::TestApp;
3964 use std::sync::Arc;
3965
3966 const CELL_BACKGROUND: u32 = 0x11aa77;
3967
3968 struct TableRoot {
3969 text_view: Entity<TextViewState>,
3970 width: Pixels,
3971 style: TextViewStyle,
3972 }
3973
3974 impl Render for TableRoot {
3975 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3976 div()
3977 .w(self.width)
3978 .child(TextView::new(&self.text_view).style(self.style.clone()))
3979 }
3980 }
3981
3982 let short = "Operating revenue (USD)";
3983 let source = format!(
3984 "| {short} | Note |\n| --- | --- |\n| {short} | x |\n| 1 | {} |",
3985 "word ".repeat(30)
3986 );
3987 let first_column = |width: f32, style: TextViewStyle| {
3989 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3990 app.update(crate::init);
3991 let cell = style.table_cell().clone().bg(gpui::rgb(CELL_BACKGROUND));
3992 let style = style.with_table_cell(cell);
3993 let mut window = app.open_window(|_, cx| TableRoot {
3994 text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
3995 width: px(width),
3996 style,
3997 });
3998 window.draw();
3999 app.run_until_parked();
4000 window.draw();
4001 window.update(|_, window, _| {
4002 let background: gpui::Background = gpui::rgb(CELL_BACKGROUND).into();
4003 let cells: Vec<_> = window
4004 .painted_quads()
4005 .into_iter()
4006 .filter(|quad| quad.background == background)
4007 .map(|quad| quad.bounds)
4008 .collect();
4009 let left = cells.iter().map(|bounds| bounds.origin.x).min().unwrap();
4010 let mut column: Vec<_> = cells
4011 .into_iter()
4012 .filter(|bounds| bounds.origin.x == left)
4013 .collect();
4014 column.sort_by_key(|bounds| bounds.origin.y);
4015 column
4016 .iter()
4017 .map(|bounds| bounds.size.height)
4018 .collect::<Vec<_>>()
4019 })
4020 };
4021 let scroll = || {
4022 let mut table = StyleRefinement::default();
4023 table.overflow.x = Some(gpui::Overflow::Scroll);
4024 TextViewStyle::default().with_table(table)
4025 };
4026
4027 for (layout, style) in [("wrap", TextViewStyle::default()), ("scroll", scroll())] {
4028 let fits = first_column(4000., style.clone());
4029 let narrow = first_column(700., style);
4030 assert_eq!(fits.len(), 3, "{layout}: three rows");
4031 assert_eq!(fits[0], fits[2], "{layout}: the header fits on one line");
4032 assert_eq!(narrow[..2], fits[..2], "{layout}: the short column wraps");
4033 }
4034
4035 let single_line = first_column(4000., TextViewStyle::default())[0];
4036 let padded = TextViewStyle::default().with_table_cell(StyleRefinement::default().px_4());
4037 assert_eq!(
4038 first_column(4000., padded)[0],
4039 single_line,
4040 "the cell padding refinement leaves the text its measured width"
4041 );
4042 let bold = TextViewStyle::default()
4043 .with_table(StyleRefinement::default().font_weight(gpui::FontWeight::BOLD));
4044 assert_eq!(
4045 first_column(4000., bold)[0],
4046 single_line,
4047 "the table text refinement is measured"
4048 );
4049 }
4050
4051 #[gpui::test]
4052 fn link_tooltip_shows_on_one_of_two_renderings_of_a_document(cx: &mut TestAppContext) {
4053 struct Preview;
4054 impl Render for Preview {
4055 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4056 div()
4057 .debug_selector(|| "link-destination-preview".into())
4058 .child("/tmp/report.json")
4059 }
4060 }
4061 struct Twice {
4062 view: Entity<TextViewState>,
4063 }
4064 impl Render for Twice {
4065 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4066 div()
4067 .child(
4068 TextView::new(&self.view)
4069 .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
4070 )
4071 .child(
4072 TextView::new(&self.view)
4073 .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
4074 )
4075 }
4076 }
4077 cx.update(crate::init);
4078 let (root, cx) = cx.add_window_view(|_, cx| Twice {
4079 view: cx.new(|cx| {
4080 TextViewState::markdown("[preview destination](file:///tmp/report.json)", cx)
4081 }),
4082 });
4083 cx.run_until_parked();
4084 cx.update(|window, cx| window.draw(cx).clear(cx));
4085 let bounds = root.read_with(cx, |root, cx| {
4086 root.view.read(cx).selection_adapter.text_bounds()[0]
4087 });
4088 let start = point(bounds.left() + px(2.), bounds.center().y);
4089 cx.update(|window, cx| window.simulate_mouse_move(start, cx));
4090 cx.run_until_parked();
4091 let mut requested = 0;
4092 for _ in 0..3 {
4093 cx.update(|window, cx| window.draw(cx).clear(cx));
4094 requested = cx.update(|window, cx| window.simulate_next_frame(cx));
4095 cx.run_until_parked();
4096 }
4097 assert_eq!(requested, 0, "a settled hover stops redrawing");
4098 cx.update(|window, cx| window.draw(cx).clear(cx));
4099 assert!(
4100 cx.debug_bounds("link-destination-preview").is_some(),
4101 "the hovered rendering shows its destination"
4102 );
4103 }
4104
4105 #[gpui::test]
4106 fn link_tooltip_follows_the_pointer_and_clears_on_exit(cx: &mut TestAppContext) {
4107 struct Preview;
4108 impl Render for Preview {
4109 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4110 div()
4111 .debug_selector(|| "link-destination-preview".into())
4112 .w(px(180.))
4113 .h(px(24.))
4114 .child("/tmp/report.json")
4115 }
4116 }
4117 struct Root {
4118 view: Entity<TextViewState>,
4119 covered: bool,
4120 }
4121 impl Render for Root {
4122 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4123 div()
4124 .relative()
4125 .child(
4126 TextView::new(&self.view)
4127 .w(px(160.))
4128 .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
4129 )
4130 .when(self.covered, |view| {
4131 view.child(div().absolute().top_0().left_0().size_full().occlude())
4132 })
4133 }
4134 }
4135 cx.update(crate::init);
4136 let (root, cx) = cx.add_window_view(|_, cx| Root {
4137 covered: true,
4138 view: cx.new(|cx| {
4139 TextViewState::markdown("[preview destination with a label that wraps over several lines](file:///tmp/report.json)", cx)
4140 }),
4141 });
4142 cx.run_until_parked();
4143 cx.update(|window, cx| window.draw(cx).clear(cx));
4144 let rows = root.read_with(cx, |root, cx| {
4145 root.view.read(cx).selection_adapter.text_bounds()
4146 });
4147 assert!(rows.len() > 1, "the native link label wraps");
4148 let bounds = rows[0];
4149 let start = point(bounds.left() + px(2.), bounds.center().y);
4150 cx.update(|window, cx| window.simulate_mouse_move(start, cx));
4151 cx.run_until_parked();
4152 cx.update(|window, cx| window.draw(cx).clear(cx));
4153 assert!(
4154 cx.debug_bounds("link-destination-preview").is_none(),
4155 "an occluded link cannot activate a preview"
4156 );
4157 root.update(cx, |root, cx| {
4158 root.covered = false;
4159 cx.notify();
4160 });
4161 cx.run_until_parked();
4162 cx.update(|window, cx| window.draw(cx).clear(cx));
4163 assert_eq!(
4164 cx.update(|window, cx| window.simulate_next_frame(cx)),
4165 1,
4166 "a new hover requests the frame that shows its preview",
4167 );
4168 cx.run_until_parked();
4169 cx.update(|window, cx| window.draw(cx).clear(cx));
4170 let first = cx
4171 .debug_bounds("link-destination-preview")
4172 .expect("hovering a native link paints its destination preview");
4173 assert_eq!(
4174 cx.update(|window, cx| window.simulate_next_frame(cx)),
4175 0,
4176 "an idle preview does not request more frames",
4177 );
4178 cx.update(|window, cx| window.simulate_mouse_move(start + point(px(20.), px(0.)), cx));
4179 cx.run_until_parked();
4180 cx.update(|window, cx| window.draw(cx).clear(cx));
4181 let second = cx.debug_bounds("link-destination-preview").unwrap();
4182 assert_eq!(second.left() - first.left(), px(20.));
4183 assert_eq!(second.top(), first.top());
4184 cx.update(|window, cx| window.simulate_mouse_move(rows[1].center(), cx));
4185 cx.run_until_parked();
4186 cx.update(|window, cx| window.draw(cx).clear(cx));
4187 assert!(cx.debug_bounds("link-destination-preview").is_some());
4188 root.update(cx, |root, cx| {
4189 root.covered = true;
4190 cx.notify();
4191 });
4192 cx.run_until_parked();
4193 cx.update(|window, cx| window.draw(cx).clear(cx));
4194 assert!(
4195 cx.debug_bounds("link-destination-preview").is_none(),
4196 "covering an active link clears its preview"
4197 );
4198 root.update(cx, |root, cx| {
4199 root.covered = false;
4200 cx.notify();
4201 });
4202 cx.run_until_parked();
4203 cx.update(|window, cx| {
4204 window.simulate_mouse_move(point(bounds.right() + px(30.), bounds.center().y), cx)
4205 });
4206 cx.run_until_parked();
4207 cx.update(|window, cx| window.draw(cx).clear(cx));
4208 assert!(cx.debug_bounds("link-destination-preview").is_none());
4209 }
4210
4211 #[gpui::test]
4212 fn markdown_link_opens_url_without_handler(cx: &mut TestAppContext) {
4213 cx.update(crate::init);
4214 let (_, cx) =
4215 cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
4216 let cx: &mut VisualTestContext = cx;
4217
4218 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
4219
4220 assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
4221 }
4222
4223 #[gpui::test]
4224 fn right_click_does_not_open_url_without_handler(cx: &mut TestAppContext) {
4225 cx.update(crate::init);
4226 let (_, cx) =
4227 cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
4228 let cx: &mut VisualTestContext = cx;
4229
4230 cx.simulate_mouse_down(
4231 point(px(10.), px(10.)),
4232 MouseButton::Right,
4233 Modifiers::default(),
4234 );
4235 cx.simulate_mouse_up(
4236 point(px(10.), px(10.)),
4237 MouseButton::Right,
4238 Modifiers::default(),
4239 );
4240
4241 assert_eq!(cx.opened_url(), None);
4242 }
4243
4244 #[gpui::test]
4245 fn link_handler_receives_button_and_modifiers(cx: &mut TestAppContext) {
4246 use std::sync::{Arc, Mutex};
4247
4248 struct LinkRoot {
4249 text_view: Entity<TextViewState>,
4250 clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
4251 }
4252
4253 impl Render for LinkRoot {
4254 fn render(
4255 &mut self,
4256 _window: &mut Window,
4257 _cx: &mut Context<Self>,
4258 ) -> impl IntoElement {
4259 let clicks = self.clicks.clone();
4260 div()
4261 .w(px(240.))
4262 .child(
4263 TextView::new(&self.text_view).on_link_click(move |url, event, _, _| {
4264 clicks.lock().unwrap().push((url.clone(), event.clone()));
4265 }),
4266 )
4267 }
4268 }
4269
4270 cx.update(crate::init);
4271 let clicks = Arc::new(Mutex::new(Vec::new()));
4272 let captured = clicks.clone();
4273 let (_, cx) = cx.add_window_view(move |_, cx| LinkRoot {
4274 text_view: cx.new(|cx| TextViewState::markdown("[example](https://example.com)", cx)),
4275 clicks,
4276 });
4277 let cx: &mut VisualTestContext = cx;
4278
4279 let mut modifiers = Modifiers::default();
4280 modifiers.control = true;
4281 cx.simulate_click(point(px(10.), px(10.)), modifiers);
4282 cx.simulate_mouse_down(
4283 point(px(10.), px(10.)),
4284 MouseButton::Middle,
4285 Modifiers::default(),
4286 );
4287 cx.simulate_mouse_up(
4288 point(px(10.), px(10.)),
4289 MouseButton::Middle,
4290 Modifiers::default(),
4291 );
4292 cx.simulate_mouse_down(
4293 point(px(10.), px(10.)),
4294 MouseButton::Right,
4295 Modifiers::default(),
4296 );
4297 cx.simulate_mouse_up(
4298 point(px(10.), px(10.)),
4299 MouseButton::Right,
4300 Modifiers::default(),
4301 );
4302
4303 let clicks = captured.lock().unwrap();
4304 assert_eq!(clicks.len(), 3);
4305 assert_eq!(clicks[0].0, "https://example.com");
4306 assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
4307 assert!(clicks[0].1.modifiers().control);
4308 assert!(clicks[1].1.is_middle_click());
4309 assert!(clicks[2].1.is_right_click());
4310 assert_eq!(cx.opened_url(), None);
4311 }
4312
4313 #[gpui::test]
4314 fn inline_object_inherits_bold_and_link_clicks_without_opening_on_drag(
4315 cx: &mut TestAppContext,
4316 ) {
4317 use std::sync::{Arc, Mutex};
4318 struct Root {
4319 state: Entity<TextViewState>,
4320 clicks: Arc<Mutex<Vec<SharedString>>>,
4321 }
4322 impl Render for Root {
4323 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4324 let clicks = self.clicks.clone();
4325 let extensions = crate::text::MarkdownExtensions::default().plugin(
4326 crate::text::markdown_ext::TestInlinePlugin::new("math")
4327 .parse_with(|node, _| {
4328 matches!(node, markdown::mdast::Node::InlineMath(_)).then(|| {
4329 super::super::MarkdownNode::new("math", ()).text("formula")
4330 })
4331 })
4332 .render_with(|_, context, _, _| {
4333 assert_eq!(context.text_style().font_weight, gpui::FontWeight::BOLD);
4334 Some(super::super::InlineElement::new(div().child("formula")))
4335 }),
4336 );
4337 div().w(px(300.)).child(crate::TextSelectionLayer).child(
4338 TextView::new(&self.state)
4339 .markdown_extensions(extensions)
4340 .on_link_click(move |url, _, _, _| {
4341 clicks.lock().unwrap().push(url.clone())
4342 }),
4343 )
4344 }
4345 }
4346 cx.update(crate::init);
4347 let clicks = Arc::new(Mutex::new(Vec::new()));
4348 let captured = clicks.clone();
4349 let (root, cx) = cx.add_window_view(move |_, cx| Root {
4350 state: cx.new(|cx| TextViewState::markdown("**[$x$](https://example.com)**", cx)),
4351 clicks,
4352 });
4353 let cx: &mut VisualTestContext = cx;
4354 cx.run_until_parked();
4355 cx.update(|window, cx| {
4356 let _ = window.draw(cx);
4357 });
4358 let bounds = root.read_with(cx, |root, cx| {
4359 root.state.read(cx).selection_adapter.text_bounds()[0]
4360 });
4361 for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
4362 cx.simulate_mouse_down(bounds.center(), button, Modifiers::default());
4363 cx.simulate_mouse_up(bounds.center(), button, Modifiers::default());
4364 }
4365 assert_eq!(captured.lock().unwrap().len(), 3);
4366 let start = point(bounds.left() + px(1.), bounds.center().y);
4367 let end = point(bounds.right() - px(1.), bounds.center().y);
4368 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
4369 cx.update(|window, cx| {
4370 let _ = window.draw(cx);
4371 });
4372 cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
4373 cx.update(|window, cx| {
4374 let _ = window.draw(cx);
4375 });
4376 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
4377 assert_eq!(captured.lock().unwrap().len(), 3);
4378 }
4379
4380 #[gpui::test]
4381 fn linked_image_handler_receives_left_middle_and_right_clicks(cx: &mut TestAppContext) {
4382 use std::sync::{Arc, Mutex};
4383
4384 struct LinkedImageRoot {
4385 text_view: Entity<TextViewState>,
4386 clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
4387 }
4388
4389 impl Render for LinkedImageRoot {
4390 fn render(
4391 &mut self,
4392 _window: &mut Window,
4393 _cx: &mut Context<Self>,
4394 ) -> impl IntoElement {
4395 let clicks = self.clicks.clone();
4396 div().w(px(160.)).child(
4397 TextView::new(&self.text_view)
4398 .selectable(true)
4399 .on_link_click(move |url, event, _, _| {
4400 clicks.lock().unwrap().push((url.clone(), event.clone()));
4401 }),
4402 )
4403 }
4404 }
4405
4406 cx.update(crate::init);
4407 let clicks = Arc::new(Mutex::new(Vec::new()));
4408 let captured = clicks.clone();
4409 let (content, cx) = cx.add_window_view(move |_, cx| LinkedImageRoot {
4410 text_view: cx.new(|cx| {
4411 TextViewState::markdown(
4412 r#"Before [<img src="https://example.com/image.svg" width="32" height="32">](https://example.com/image-link) after."#,
4413 cx,
4414 )
4415 }),
4416 clicks,
4417 }
4418 );
4419 let cx: &mut VisualTestContext = cx;
4420 cx.run_until_parked();
4421 cx.update(|window, cx| {
4422 let _ = window.draw(cx);
4423 });
4424
4425 let inline_bounds = content.read_with(cx, |content, cx| {
4426 content.text_view.read(cx).selection_adapter.text_bounds()
4427 });
4428 assert!(
4429 inline_bounds.len() >= 2,
4430 "linked image needs text bounds on both sides: {inline_bounds:?}"
4431 );
4432 assert!(
4433 inline_bounds[1].left() - inline_bounds[0].right() >= px(24.),
4434 "linked image did not reserve the expected click target: {inline_bounds:?}"
4435 );
4436 let position = point(
4437 inline_bounds[0].right() + (inline_bounds[1].left() - inline_bounds[0].right()) * 0.5,
4438 inline_bounds[0].top() + px(8.),
4439 );
4440 for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
4441 cx.simulate_mouse_down(position, button, Modifiers::default());
4442 cx.simulate_mouse_up(position, button, Modifiers::default());
4443 }
4444
4445 let clicks = captured.lock().unwrap();
4446 assert_eq!(clicks.len(), 3);
4447 assert!(
4448 clicks
4449 .iter()
4450 .all(|(url, _)| url == "https://example.com/image-link")
4451 );
4452 assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
4453 assert!(clicks[1].1.is_middle_click());
4454 assert!(clicks[2].1.is_right_click());
4455 assert_eq!(cx.opened_url(), None);
4456 }
4457
4458 #[gpui::test]
4459 fn clipped_markdown_cannot_start_selection(cx: &mut TestAppContext) {
4460 cx.update(crate::init);
4461 let (view, cx) = cx
4462 .add_window_view(|_, cx| TextViewTestRoot::new("visible\n\nhidden selection text", cx));
4463 let cx: &mut VisualTestContext = cx;
4464
4465 cx.simulate_mouse_down(
4466 point(px(10.), px(34.)),
4467 MouseButton::Left,
4468 Modifiers::default(),
4469 );
4470 cx.simulate_mouse_move(
4471 point(px(90.), px(34.)),
4472 Some(MouseButton::Left),
4473 Modifiers::default(),
4474 );
4475 cx.simulate_mouse_up(
4476 point(px(90.), px(34.)),
4477 MouseButton::Left,
4478 Modifiers::default(),
4479 );
4480
4481 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4482 assert!(
4483 selected_text.is_empty(),
4484 "unexpected selection: {selected_text:?}"
4485 );
4486 }
4487
4488 struct ClippedTallTextViewTestRoot {
4492 text_view: Entity<TextViewState>,
4493 }
4494
4495 impl ClippedTallTextViewTestRoot {
4496 fn new(cx: &mut Context<Self>) -> Self {
4497 let text_view =
4501 cx.new(|cx| TextViewState::markdown("alpha\n\nbravo\n\ncharlie\n\ndelta", cx));
4502 Self { text_view }
4503 }
4504 }
4505
4506 impl Render for ClippedTallTextViewTestRoot {
4507 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4508 div()
4509 .w(px(200.))
4510 .child(crate::TextSelectionLayer)
4511 .child(
4512 div()
4513 .h(px(40.))
4514 .overflow_hidden()
4515 .child(TextView::new(&self.text_view).selectable(true)),
4516 )
4517 .child(div().h(px(160.)))
4520 }
4521 }
4522
4523 #[gpui::test]
4532 fn selection_band_beyond_clip_copies_offscreen_text(cx: &mut TestAppContext) {
4533 cx.update(crate::init);
4534 let (content, cx) = cx.add_window_view(|_, cx| ClippedTallTextViewTestRoot::new(cx));
4535 let cx: &mut VisualTestContext = cx;
4536
4537 cx.run_until_parked();
4538 cx.update(|window, cx| {
4539 let _ = window.draw(cx);
4540 });
4541
4542 cx.simulate_mouse_down(
4546 point(px(2.), px(8.)),
4547 MouseButton::Left,
4548 Modifiers::default(),
4549 );
4550 cx.update(|window, cx| {
4551 let _ = window.draw(cx);
4552 });
4553 cx.simulate_mouse_move(
4554 point(px(180.), px(150.)),
4555 Some(MouseButton::Left),
4556 Modifiers::default(),
4557 );
4558 cx.update(|window, cx| {
4559 let _ = window.draw(cx);
4560 });
4561 cx.simulate_mouse_up(
4562 point(px(180.), px(150.)),
4563 MouseButton::Left,
4564 Modifiers::default(),
4565 );
4566 cx.update(|window, cx| {
4567 let _ = window.draw(cx);
4568 });
4569
4570 let selected_text =
4571 content.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4572 assert!(
4573 selected_text.contains("delta"),
4574 "clipped-out text was not copied: {selected_text:?}"
4575 );
4576 assert!(
4577 selected_text.contains("charlie"),
4578 "clipped-out text was not copied: {selected_text:?}"
4579 );
4580 }
4581
4582 #[gpui::test]
4583 fn double_click_selects_word(cx: &mut TestAppContext) {
4584 cx.update(crate::init);
4585 let (view, cx) =
4586 cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
4587
4588 let cx: &mut VisualTestContext = cx;
4589 cx.run_until_parked();
4590 cx.update(|window, cx| {
4591 let _ = window.draw(cx);
4592 });
4593 let position = point(px(10.), px(16.));
4594 cx.simulate_event(MouseDownEvent {
4595 position,
4596 modifiers: Modifiers::default(),
4597 button: MouseButton::Left,
4598 click_count: 2,
4599 first_mouse: false,
4600 });
4601 cx.simulate_event(MouseUpEvent {
4602 position,
4603 modifiers: Modifiers::default(),
4604 button: MouseButton::Left,
4605 click_count: 2,
4606 });
4607 cx.update(|window, cx| {
4608 let _ = window.draw(cx);
4609 });
4610
4611 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4612 assert_eq!(selected_text.trim(), "quick");
4613 }
4614
4615 #[gpui::test]
4616 fn long_press_selects_word_then_drag_extends_selection(cx: &mut TestAppContext) {
4617 struct TouchRoot {
4618 text_view: Entity<TextViewState>,
4619 }
4620 impl Render for TouchRoot {
4621 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4622 div()
4623 .w(px(300.))
4624 .child(crate::TextSelectionLayer)
4625 .child(TextView::new(&self.text_view).selectable(true))
4626 }
4627 }
4628 cx.update(crate::init);
4629 let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
4630 text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
4631 });
4632 cx.run_until_parked();
4633 cx.update(|window, cx| {
4634 let _ = window.draw(cx);
4635 });
4636 let start_position = point(px(10.), px(16.));
4637 cx.simulate_event(gpui::LongPressEvent {
4638 phase: gpui::TouchPhase::Started,
4639 start_position,
4640 position: start_position,
4641 });
4642 cx.update(|window, cx| {
4643 let _ = window.draw(cx);
4644 });
4645 assert_eq!(
4646 view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4647 .trim(),
4648 "quick"
4649 );
4650 for phase in [gpui::TouchPhase::Moved, gpui::TouchPhase::Ended] {
4651 cx.simulate_event(gpui::LongPressEvent {
4652 phase,
4653 start_position,
4654 position: point(px(220.), px(16.)),
4655 });
4656 }
4657 cx.update(|window, cx| {
4658 let _ = window.draw(cx);
4659 });
4660 assert_eq!(
4661 view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4662 .trim(),
4663 "quick select value"
4664 );
4665 }
4666
4667 #[gpui::test]
4668 fn long_press_release_keeps_handles_which_drag_the_selection(cx: &mut TestAppContext) {
4669 use crate::{SelectionEdge, TextSelection};
4670
4671 struct TouchRoot {
4672 text_view: Entity<TextViewState>,
4673 }
4674 impl Render for TouchRoot {
4675 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4676 div()
4677 .w(px(300.))
4678 .child(crate::TextSelectionLayer)
4679 .child(TextView::new(&self.text_view).selectable(true))
4680 }
4681 }
4682 cx.update(crate::init);
4683 let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
4684 text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
4685 });
4686 let draw = |cx: &mut VisualTestContext| {
4687 cx.update(|window, cx| {
4688 let _ = window.draw(cx);
4689 });
4690 };
4691 let selected = |cx: &mut VisualTestContext| {
4692 view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4693 .trim()
4694 .to_string()
4695 };
4696 cx.run_until_parked();
4697 draw(cx);
4698
4699 let start_position = point(px(70.), px(16.));
4700 for phase in [gpui::TouchPhase::Started, gpui::TouchPhase::Ended] {
4701 cx.simulate_event(gpui::LongPressEvent {
4702 phase,
4703 start_position,
4704 position: start_position,
4705 });
4706 draw(cx);
4707 }
4708 assert_eq!(selected(cx), "select");
4709 let snapshot = cx
4710 .update(|window, cx| TextSelection::touch_selection(window, cx))
4711 .expect("a released long press keeps its handles");
4712 assert!(snapshot.is_menu_open());
4713 assert!(!snapshot.is_empty());
4714 assert!(snapshot.start().left() < snapshot.end().left());
4715
4716 let end = snapshot.end();
4719 let finger = point(end.left(), end.bottom() + px(20.));
4720 cx.update(|window, cx| {
4721 TextSelection::begin_edge_drag(SelectionEdge::End, finger, window, cx);
4722 });
4723 draw(cx);
4724 let snapshot = cx
4725 .update(|window, cx| TextSelection::touch_selection(window, cx))
4726 .unwrap();
4727 assert_eq!(snapshot.dragging(), Some(SelectionEdge::End));
4728 assert!(!snapshot.is_menu_open());
4729 cx.update(|window, cx| {
4730 TextSelection::update_edge_drag(point(px(290.), finger.y), window, cx);
4731 });
4732 draw(cx);
4733 assert_eq!(selected(cx), "select value");
4734 cx.update(|window, cx| TextSelection::end_edge_drag(window, cx));
4735 draw(cx);
4736 let snapshot = cx
4737 .update(|window, cx| TextSelection::touch_selection(window, cx))
4738 .unwrap();
4739 assert!(snapshot.is_menu_open());
4740 assert_eq!(snapshot.dragging(), None);
4741 let select_start = snapshot.start().left();
4742
4743 cx.update(|_, cx| {
4746 view.update(cx, |root, cx| {
4747 root.text_view.update(cx, |state, cx| state.select_all(cx));
4748 });
4749 });
4750 draw(cx);
4751 assert_eq!(selected(cx), "quick select value");
4752 let snapshot = cx
4753 .update(|window, cx| TextSelection::touch_selection(window, cx))
4754 .expect("select all keeps the touch selection");
4755 let start = snapshot.start();
4756 cx.update(|window, cx| {
4757 TextSelection::begin_edge_drag(SelectionEdge::Start, start.origin, window, cx);
4758 TextSelection::update_edge_drag(point(select_start, start.origin.y), window, cx);
4759 TextSelection::end_edge_drag(window, cx);
4760 });
4761 draw(cx);
4762 assert_eq!(selected(cx), "select value");
4763
4764 let menu = gpui::Bounds::new(point(px(0.), px(200.)), gpui::size(px(120.), px(32.)));
4767 cx.update(|window, cx| TextSelection::register_touch_ui(menu, window, cx));
4768 cx.simulate_event(MouseDownEvent {
4769 position: point(px(10.), px(210.)),
4770 modifiers: Modifiers::default(),
4771 button: MouseButton::Left,
4772 click_count: 1,
4773 first_mouse: false,
4774 });
4775 assert_eq!(selected(cx), "select value");
4776 cx.simulate_event(MouseDownEvent {
4777 position: point(px(10.), px(16.)),
4778 modifiers: Modifiers::default(),
4779 button: MouseButton::Left,
4780 click_count: 1,
4781 first_mouse: false,
4782 });
4783 cx.simulate_event(MouseUpEvent {
4784 position: point(px(10.), px(16.)),
4785 modifiers: Modifiers::default(),
4786 button: MouseButton::Left,
4787 click_count: 1,
4788 });
4789 draw(cx);
4790 assert!(
4791 cx.update(|window, cx| TextSelection::touch_selection(window, cx))
4792 .is_none()
4793 );
4794 }
4795
4796 #[gpui::test]
4797 fn triple_click_selects_paragraph(cx: &mut TestAppContext) {
4798 cx.update(crate::init);
4799 let (view, cx) =
4800 cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
4801
4802 let cx: &mut VisualTestContext = cx;
4803 cx.run_until_parked();
4804 cx.update(|window, cx| {
4805 let _ = window.draw(cx);
4806 });
4807
4808 let position = point(px(10.), px(10.));
4809 cx.simulate_event(MouseDownEvent {
4810 position,
4811 modifiers: Modifiers::default(),
4812 button: MouseButton::Left,
4813 click_count: 3,
4814 first_mouse: false,
4815 });
4816 cx.simulate_event(MouseUpEvent {
4817 position,
4818 modifiers: Modifiers::default(),
4819 button: MouseButton::Left,
4820 click_count: 3,
4821 });
4822 cx.update(|window, cx| {
4823 let _ = window.draw(cx);
4824 });
4825
4826 let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4827 assert_eq!(selected_text.trim(), "quick select value");
4828 }
4829
4830 mod multi_click_drag {
4831 use super::*;
4832
4833 struct Root {
4834 text_view: Entity<TextViewState>,
4835 }
4836
4837 impl Render for Root {
4838 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4839 div()
4840 .w(px(400.))
4841 .child(crate::TextSelectionLayer)
4842 .child(TextView::new(&self.text_view).selectable(true))
4843 }
4844 }
4845
4846 fn setup<'a>(
4847 markdown: &str,
4848 cx: &'a mut TestAppContext,
4849 ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
4850 cx.update(crate::init);
4851 let (root, cx) = cx.add_window_view(|_, cx| Root {
4852 text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
4853 });
4854 cx.run_until_parked();
4855 cx.update(|window, cx| window.draw(cx).clear(cx));
4856 (root.read_with(cx, |root, _| root.text_view.clone()), cx)
4857 }
4858
4859 fn position(
4861 state: &Entity<TextViewState>,
4862 text: &str,
4863 index: usize,
4864 cx: &mut VisualTestContext,
4865 ) -> gpui::Point<Pixels> {
4866 state.read_with(cx, |state, _| {
4867 state.selection_adapter.text_position(text, index)
4868 })
4869 }
4870
4871 fn press(
4872 position: gpui::Point<Pixels>,
4873 click_count: usize,
4874 shift: bool,
4875 cx: &mut VisualTestContext,
4876 ) {
4877 cx.simulate_event(MouseDownEvent {
4878 position,
4879 modifiers: Modifiers {
4880 shift,
4881 ..Default::default()
4882 },
4883 button: MouseButton::Left,
4884 click_count,
4885 first_mouse: false,
4886 });
4887 }
4888
4889 fn drag(position: gpui::Point<Pixels>, cx: &mut VisualTestContext) {
4890 cx.simulate_event(gpui::MouseMoveEvent {
4891 position,
4892 pressed_button: Some(MouseButton::Left),
4893 modifiers: Modifiers::default(),
4894 });
4895 }
4896
4897 fn release(position: gpui::Point<Pixels>, click_count: usize, cx: &mut VisualTestContext) {
4898 cx.simulate_event(MouseUpEvent {
4899 position,
4900 modifiers: Modifiers::default(),
4901 button: MouseButton::Left,
4902 click_count,
4903 });
4904 }
4905
4906 fn selected(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> String {
4907 cx.update(|window, cx| window.draw(cx).clear(cx));
4908 state.read_with(cx, |state, _| state.selected_text().trim().to_string())
4909 }
4910
4911 #[gpui::test]
4912 fn double_click_drag_extends_the_selection_by_words(cx: &mut TestAppContext) {
4913 let (first, second) = ("alpha beta gamma", "delta epsilon zeta");
4914 let (state, cx) = setup(&format!("{first}\n\n{second}"), cx);
4915
4916 press(position(&state, first, 7, cx), 2, false, cx);
4917 assert_eq!(selected(&state, cx), "beta");
4918 drag(position(&state, first, 8, cx), cx);
4919 assert_eq!(selected(&state, cx), "beta");
4920 drag(position(&state, first, 13, cx), cx);
4921 assert_eq!(selected(&state, cx), "beta gamma");
4922 drag(position(&state, first, 1, cx), cx);
4924 assert_eq!(selected(&state, cx), "alpha beta");
4925 let end = position(&state, second, 8, cx);
4926 drag(end, cx);
4927 assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
4928 release(end, 2, cx);
4929 assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
4930 }
4931
4932 #[gpui::test]
4933 fn triple_click_drag_extends_the_selection_by_paragraphs(cx: &mut TestAppContext) {
4934 let (state, cx) = setup("first one\n\nsecond one\n\nthird one", cx);
4935
4936 press(position(&state, "second one", 2, cx), 3, false, cx);
4937 assert_eq!(selected(&state, cx), "second one");
4938 drag(position(&state, "third one", 2, cx), cx);
4939 assert_eq!(selected(&state, cx), "second one\nthird one");
4940 let end = position(&state, "first one", 2, cx);
4941 drag(end, cx);
4942 assert_eq!(selected(&state, cx), "first one\nsecond one");
4943 release(end, 3, cx);
4944 assert_eq!(selected(&state, cx), "first one\nsecond one");
4945 }
4946
4947 #[gpui::test]
4949 fn triple_click_drag_and_shift_click_keep_hard_break_paragraphs_whole(
4950 cx: &mut TestAppContext,
4951 ) {
4952 let first = "first top\nfirst bottom";
4953 let last = "last top\nlast bottom";
4954 let (state, cx) = setup(
4955 "first top \nfirst bottom\n\nmiddle\n\nlast top \nlast bottom",
4956 cx,
4957 );
4958
4959 press(position(&state, "middle", 2, cx), 3, false, cx);
4960 assert_eq!(selected(&state, cx), "middle");
4961 let after = position(&state, last, 2, cx);
4962 drag(after, cx);
4963 assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4964 let before = position(&state, first, "first top\n".len() + 2, cx);
4965 drag(before, cx);
4966 assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4967 release(before, 3, cx);
4968
4969 press(after, 1, true, cx);
4970 release(after, 1, cx);
4971 assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4972 press(before, 1, true, cx);
4973 release(before, 1, cx);
4974 assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4975 }
4976
4977 #[gpui::test]
4979 fn multi_click_drag_snaps_across_inline_code(cx: &mut TestAppContext) {
4980 let (state, cx) = setup("plain words\n\nuse `code` in here", cx);
4981
4982 press(position(&state, "plain words", 8, cx), 2, false, cx);
4983 drag(position(&state, " in here", 6, cx), cx);
4984 assert_eq!(selected(&state, cx), "words\nuse code in here");
4985 release(position(&state, " in here", 6, cx), 2, cx);
4986
4987 press(position(&state, "plain words", 2, cx), 3, false, cx);
4988 assert_eq!(selected(&state, cx), "plain words");
4989 drag(position(&state, "use ", 1, cx), cx);
4990 assert_eq!(selected(&state, cx), "plain words\nuse code in here");
4991 }
4992
4993 #[gpui::test]
4994 fn shift_click_after_a_double_click_extends_by_words(cx: &mut TestAppContext) {
4995 let text = "alpha beta gamma";
4996 let (state, cx) = setup(text, cx);
4997
4998 let word = position(&state, text, 7, cx);
4999 press(word, 2, false, cx);
5000 release(word, 2, cx);
5001 let after = position(&state, text, 13, cx);
5002 press(after, 1, true, cx);
5003 release(after, 1, cx);
5004 assert_eq!(selected(&state, cx), "beta gamma");
5005 let before = position(&state, text, 1, cx);
5006 press(before, 1, true, cx);
5007 release(before, 1, cx);
5008 assert_eq!(selected(&state, cx), "alpha beta");
5009 }
5010 }
5011
5012 mod copy_before_paint {
5013 use super::*;
5014 use crate::{TextSelection, text::SelectionFormat};
5015
5016 const MARKDOWN: &str = "中文 **café**\n\nβeta `\u{2009}code\u{2009}` 👩💻\n\n終わり";
5017 const PLAIN: &str = "中文 café\nβeta \u{2009}code\u{2009} 👩💻\n終わり\n";
5018
5019 struct Root {
5020 state: Entity<TextViewState>,
5021 format: SelectionFormat,
5022 width: Pixels,
5023 scrollable: bool,
5024 }
5025
5026 impl Render for Root {
5027 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5028 div()
5029 .w(self.width)
5030 .when(self.scrollable, |el| el.h(px(160.)))
5031 .child(crate::TextSelectionLayer)
5032 .child(
5033 TextView::new(&self.state)
5034 .scrollable(self.scrollable)
5035 .selection_format(self.format),
5036 )
5037 }
5038 }
5039
5040 fn setup(
5041 format: SelectionFormat,
5042 cx: &mut TestAppContext,
5043 ) -> (Entity<TextViewState>, &mut VisualTestContext) {
5044 cx.update(crate::init);
5045 let (root, cx) = cx.add_window_view(|_, cx| Root {
5046 state: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
5047 format,
5048 width: px(520.),
5049 scrollable: false,
5050 });
5051 cx.run_until_parked();
5052 cx.update(|window, cx| window.draw(cx).clear(cx));
5053 (root.read_with(cx, |root, _| root.state.clone()), cx)
5054 }
5055
5056 fn document<'a>(
5057 markdown: &str,
5058 format: SelectionFormat,
5059 scrollable: bool,
5060 cx: &'a mut TestAppContext,
5061 ) -> (Entity<Root>, &'a mut VisualTestContext) {
5062 cx.update(crate::init);
5063 let (root, cx) = cx.add_window_view(|_, cx| Root {
5064 state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
5065 format,
5066 width: px(520.),
5067 scrollable,
5068 });
5069 cx.run_until_parked();
5070 cx.update(|window, cx| window.draw(cx).clear(cx));
5071 (root, cx)
5072 }
5073
5074 fn scroll_to(state: &Entity<TextViewState>, ix: usize, cx: &mut VisualTestContext) {
5075 state.read_with(cx, |state, _| {
5076 state.list_state.scroll_to(gpui::ListOffset {
5077 item_ix: ix,
5078 offset_in_item: px(0.),
5079 })
5080 });
5081 cx.update(|window, cx| window.draw(cx).clear(cx));
5082 }
5083
5084 fn endpoints(
5085 state: &Entity<TextViewState>,
5086 cx: &mut VisualTestContext,
5087 ) -> (
5088 gpui::Point<Pixels>,
5089 gpui::Point<Pixels>,
5090 gpui::Point<Pixels>,
5091 ) {
5092 let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5093 let first = rows.first().unwrap();
5094 let last = rows.last().unwrap();
5095 (
5096 point(first.left() + px(0.1), first.center().y),
5097 point(first.right() - px(0.1), first.center().y),
5098 point(last.right() - px(0.1), last.center().y),
5099 )
5100 }
5101
5102 fn press(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
5105 window.dispatch_event(
5106 gpui::PlatformInput::MouseDown(MouseDownEvent {
5107 position,
5108 button: MouseButton::Left,
5109 click_count: 1,
5110 ..Default::default()
5111 }),
5112 cx,
5113 );
5114 }
5115
5116 fn extend(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
5117 window.dispatch_event(
5118 gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent {
5119 position,
5120 pressed_button: Some(MouseButton::Left),
5121 ..Default::default()
5122 }),
5123 cx,
5124 );
5125 }
5126
5127 fn release(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
5128 window.dispatch_event(
5129 gpui::PlatformInput::MouseUp(MouseUpEvent {
5130 position,
5131 button: MouseButton::Left,
5132 modifiers: Modifiers::default(),
5133 click_count: 1,
5134 }),
5135 cx,
5136 );
5137 }
5138
5139 fn assert_copy(expected: &str, window: &mut Window, cx: &mut gpui::App) {
5140 let focus = window.focused(cx).expect("gesture focuses TextView");
5143 focus.dispatch_action(&crate::input::Copy, window, cx);
5144 assert_eq!(
5145 cx.read_from_clipboard().and_then(|item| item.text()),
5146 Some(expected.trim().to_string())
5147 );
5148 assert!(focus.is_focused(window));
5149 assert_eq!(TextSelection::selected_text(window, cx), expected);
5150 }
5151
5152 #[gpui::test]
5153 fn custom_inline_and_block_copy_project_with_the_text(cx: &mut TestAppContext) {
5154 struct CustomRoot {
5155 state: Entity<TextViewState>,
5156 format: SelectionFormat,
5157 extensions: crate::text::MarkdownExtensions,
5158 }
5159 impl Render for CustomRoot {
5160 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5161 div().w(px(520.)).child(crate::TextSelectionLayer).child(
5162 TextView::new(&self.state)
5163 .selection_format(self.format)
5164 .markdown_extensions(self.extensions.clone()),
5165 )
5166 }
5167 }
5168 for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5169 cx.update(crate::init);
5170 let extensions = crate::text::MarkdownExtensions::default()
5171 .plugin(
5172 crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(
5173 |node, _| {
5174 let markdown::mdast::Node::InlineMath(math) = node else {
5175 return None;
5176 };
5177 Some(
5178 crate::text::MarkdownNode::new("math", ())
5179 .text(format!("{}²", math.value)),
5180 )
5181 },
5182 ),
5183 )
5184 .block_parser(|node, _| {
5185 matches!(node, markdown::mdast::Node::ThematicBreak(_)).then(|| {
5186 crate::text::MarkdownNode::new("block", ())
5187 .text("BLOCK")
5188 .markdown("---")
5189 })
5190 })
5191 .block_renderer("block", |_, _, _| {
5192 div()
5193 .debug_selector(|| "copy-custom-block".into())
5194 .w(px(520.))
5195 .h(px(40.))
5196 });
5197 let (root, cx) = cx.add_window_view(|_, cx| CustomRoot {
5198 state: cx
5199 .new(|cx| TextViewState::markdown("before $x$ after\n\n---\n\nlast", cx)),
5200 format,
5201 extensions,
5202 });
5203 cx.run_until_parked();
5204 cx.update(|window, cx| window.draw(cx).clear(cx));
5205 let state = root.read_with(cx, |root, _| root.state.clone());
5206 let (start, _, end) = endpoints(&state, cx);
5207 let expected = if format == SelectionFormat::Plain {
5208 "before x² after\nBLOCK\nlast\n"
5209 } else {
5210 "before $x$ after\n\n---\n\nlast"
5211 };
5212 cx.update(|window, cx| {
5213 press(start, window, cx);
5214 extend(end, window, cx);
5215 assert_copy(expected, window, cx);
5216 release(end, window, cx);
5217 });
5218 cx.update(|window, cx| window.draw(cx).clear(cx));
5219 cx.update(|window, cx| assert_copy(expected, window, cx));
5220 let block = cx.debug_bounds("copy-custom-block").unwrap();
5221 cx.update(|window, cx| {
5222 press(block.center(), window, cx);
5223 extend(point(block.center().x, block.bottom() + px(1.)), window, cx);
5224 assert_copy(
5225 if format == SelectionFormat::Plain {
5226 "BLOCK\n"
5227 } else {
5228 "---"
5229 },
5230 window,
5231 cx,
5232 );
5233 });
5234 }
5235 }
5236
5237 #[gpui::test]
5238 fn unicode_180_paragraph_copy_extends_and_retracts_before_paint(cx: &mut TestAppContext) {
5239 let markdown = (0..180)
5240 .map(|ix| format!("p{ix:03} **café** 中文 👩💻 `\u{2009}code\u{2009}`"))
5241 .collect::<Vec<_>>()
5242 .join("\n\n");
5243 let expected = (0..180)
5246 .map(|ix| format!("p{ix:03} café 中文 👩💻 \u{2009}code\u{2009}\n"))
5247 .collect::<String>();
5248 let (root, cx) = document(&markdown, SelectionFormat::Plain, false, cx);
5249 cx.simulate_resize(gpui::size(px(800.), px(12000.)));
5250 cx.update(|window, cx| window.draw(cx).clear(cx));
5251 let state = root.read_with(cx, |root, _| root.state.clone());
5252 let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5253 let first = rows.first().unwrap();
5254 let first_end = rows
5255 .iter()
5256 .take_while(|row| row.top() < first.bottom())
5257 .last()
5258 .unwrap();
5259 let last = rows.last().unwrap();
5260 assert!(last.top() > first.top() + px(3000.));
5261 let start = point(first.left() + px(0.1), first.center().y);
5262 let short_end = point(first_end.right() - px(0.1), first_end.center().y);
5263 let end = point(last.right() - px(0.1), last.center().y);
5264 let short = "p000 café 中文 👩💻 \u{2009}code\u{2009}\n";
5265 cx.update(|window, cx| {
5266 press(start, window, cx);
5267 extend(short_end, window, cx);
5268 assert_copy(short, window, cx);
5269 });
5270 cx.update(|window, cx| window.draw(cx).clear(cx));
5271 cx.update(|window, cx| {
5272 extend(end, window, cx);
5273 assert_copy(&expected, window, cx);
5274 extend(short_end, window, cx);
5275 assert_copy(short, window, cx);
5276 });
5277 }
5278
5279 #[gpui::test]
5280 fn scrolling_before_paint_keeps_the_completed_frame_coordinates(cx: &mut TestAppContext) {
5281 let markdown = format!(
5282 "{}\n\nlast",
5283 "alpha beta gamma delta epsilon zeta ".repeat(30)
5284 );
5285 let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
5286 root.update(cx, |root, cx| {
5287 root.width = px(180.);
5288 cx.notify();
5289 });
5290 cx.update(|window, cx| window.draw(cx).clear(cx));
5291 let state = root.read_with(cx, |root, _| root.state.clone());
5292 let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5293 let first = rows[0];
5294 let (start, end) = state.read_with(cx, |state, _| {
5295 (
5296 state.selection_adapter.first_text_position(0),
5297 state.selection_adapter.first_text_position("alpha".len()),
5298 )
5299 });
5300 cx.update(|window, cx| {
5301 press(start, window, cx);
5302 extend(end, window, cx);
5303 });
5304 cx.update(|window, cx| window.draw(cx).clear(cx));
5305 cx.update(|window, cx| {
5306 state.read(cx).list_state.scroll_by(first.size.height);
5307 assert_copy("alpha\n", window, cx);
5310 });
5311 }
5312
5313 #[gpui::test]
5314 fn offscreen_remeasurement_is_not_a_copy_projection(cx: &mut TestAppContext) {
5315 let markdown = (0..180)
5316 .map(|ix| format!("row {ix:03} café 中文"))
5317 .collect::<Vec<_>>()
5318 .join("\n\n");
5319 let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
5320 let state = root.read_with(cx, |root, _| root.state.clone());
5321 scroll_to(&state, 90, cx);
5322 root.update(cx, |root, cx| {
5323 root.width = px(260.);
5324 cx.notify();
5325 });
5326 cx.update(|window, cx| window.draw(cx).clear(cx));
5327 scroll_to(&state, 90, cx);
5328 let (start, end, _) = endpoints(&state, cx);
5331 cx.update(|window, cx| {
5332 press(start, window, cx);
5333 extend(end, window, cx);
5334 assert_copy("row 090 café 中文\n", window, cx);
5335 });
5336 }
5337
5338 #[gpui::test]
5339 fn virtualized_flow_retains_its_source_owned_partial_anchor(cx: &mut TestAppContext) {
5340 for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5341 let tail = (1..180)
5342 .map(|ix| format!("row {ix:03} café 中文"))
5343 .collect::<Vec<_>>();
5344 let markdown = format!("PREFIX `code` suffix\n\n{}", tail.join("\n\n"));
5345 let expected = if format == SelectionFormat::Plain {
5346 format!("code suffix\n{}\n", tail.join("\n"))
5347 } else {
5348 format!("`code` suffix\n\n{}", tail.join("\n\n"))
5349 };
5350 let (root, cx) = document(&markdown, format, true, cx);
5351 let state = root.read_with(cx, |root, _| root.state.clone());
5352 let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5353 let code = rows[1];
5354 let suffix = rows[2];
5355 assert!(code.left() < suffix.left());
5356 cx.update(|window, cx| {
5357 press(point(code.left() + px(0.1), code.center().y), window, cx);
5358 extend(
5359 point(suffix.right() - px(0.1), suffix.center().y),
5360 window,
5361 cx,
5362 );
5363 });
5364 cx.update(|window, cx| window.draw(cx).clear(cx));
5365 scroll_to(&state, 179, cx);
5366 cx.update(|window, cx| window.draw(cx).clear(cx));
5368 let (_, _, end) = endpoints(&state, cx);
5369 cx.update(|window, cx| {
5370 extend(end, window, cx);
5371 assert_copy(&expected, window, cx);
5372 });
5373 }
5374 }
5375
5376 #[gpui::test]
5377 fn a_new_range_copies_before_its_first_selection_paint(cx: &mut TestAppContext) {
5378 let (state, cx) = setup(SelectionFormat::Plain, cx);
5379 let (start, _, end) = endpoints(&state, cx);
5380 cx.update(|window, cx| {
5381 press(start, window, cx);
5382 extend(end, window, cx);
5383 assert_copy(PLAIN, window, cx);
5384 });
5385 }
5386
5387 #[gpui::test]
5388 fn an_established_range_extends_and_retracts_without_paint(cx: &mut TestAppContext) {
5389 let (state, cx) = setup(SelectionFormat::Plain, cx);
5390 let (start, first_end, end) = endpoints(&state, cx);
5391 cx.update(|window, cx| {
5392 press(start, window, cx);
5393 extend(first_end, window, cx);
5394 });
5395 cx.update(|window, cx| window.draw(cx).clear(cx));
5396 cx.update(|window, cx| {
5397 assert_copy("中文 café\n", window, cx);
5398 extend(end, window, cx);
5399 assert_copy(PLAIN, window, cx);
5400 extend(first_end, window, cx);
5401 assert_copy("中文 café\n", window, cx);
5402 });
5403 }
5404
5405 #[gpui::test]
5406 fn source_copy_projects_the_current_range_without_paint(cx: &mut TestAppContext) {
5407 let (state, cx) = setup(SelectionFormat::Source, cx);
5408 let (start, first_end, end) = endpoints(&state, cx);
5409 cx.update(|window, cx| {
5410 press(start, window, cx);
5411 extend(first_end, window, cx);
5412 assert_copy("中文 **café**", window, cx);
5413 extend(end, window, cx);
5414 assert_copy(MARKDOWN, window, cx);
5415 extend(first_end, window, cx);
5416 assert_eq!(TextSelection::selected_text(window, cx), "中文 **café**");
5417 });
5418 }
5419
5420 #[gpui::test]
5421 fn a_blank_gesture_does_not_reuse_the_previous_range(cx: &mut TestAppContext) {
5422 let (state, cx) = setup(SelectionFormat::Plain, cx);
5423 let (start, first_end, end) = endpoints(&state, cx);
5424 cx.update(|window, cx| {
5425 press(start, window, cx);
5426 extend(end, window, cx);
5427 assert_eq!(TextSelection::selected_text(window, cx), PLAIN);
5428 release(end, window, cx);
5429 press(first_end + point(px(20.), px(0.)), window, cx);
5430 extend(first_end + point(px(60.), px(0.)), window, cx);
5431 assert_eq!(TextSelection::selected_text(window, cx), "");
5432 });
5433 }
5434
5435 #[gpui::test]
5436 fn replacing_source_cannot_reproject_old_content(cx: &mut TestAppContext) {
5437 for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5438 for replacement in ["replacement".to_string(), "replacement ".repeat(500)] {
5439 let (state, cx) = setup(format, cx);
5440 let (start, _, end) = endpoints(&state, cx);
5441 cx.update(|window, cx| {
5442 press(start, window, cx);
5443 extend(end, window, cx);
5444 assert_eq!(
5445 TextSelection::selected_text(window, cx),
5446 if format == SelectionFormat::Plain {
5447 PLAIN
5448 } else {
5449 MARKDOWN
5450 }
5451 );
5452 state.update(cx, |state, cx| state.set_text(&replacement, cx));
5455 assert_eq!(TextSelection::selected_text(window, cx), "");
5456 });
5457 }
5458 }
5459 }
5460 }
5461
5462 #[gpui::test]
5468 fn outer_list_content_total_stable_while_scrolling(cx: &mut TestAppContext) {
5469 use gpui::{ListAlignment, ListState, list};
5470
5471 const ITEMS: &[&str] = &[
5472 "# Heading\n\nA paragraph long enough to wrap across several lines and produce a non-trivial height.",
5473 "Short.",
5474 "Paragraph A\n\nParagraph B\n\nParagraph C with more words to increase the height.",
5475 "## Subheading\n\n- One\n- Two\n- Three\n\nClosing paragraph.",
5476 "Only one line.",
5477 "**Bold**: medium length text with `code` mixed with regular words.",
5478 "1. First\n2. Second\n3. Third\n\nA short closing paragraph.",
5479 "A long message with enough words to wrap across multiple lines, create a taller item, and verify that off-screen measurement matches visible measurement.",
5480 ];
5481 let n = 40usize;
5482
5483 struct ListRoot {
5484 state: ListState,
5485 }
5486 impl Render for ListRoot {
5487 fn render(&mut self, _w: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5488 div().w(px(360.)).h(px(500.)).child(
5489 list(self.state.clone(), |ix, _w, _cx| {
5490 div()
5491 .w_full()
5492 .child(TextView::markdown(
5493 ("md", ix as u64),
5494 ITEMS[ix % ITEMS.len()],
5495 ))
5496 .into_any_element()
5497 })
5498 .size_full(),
5499 )
5500 }
5501 }
5502
5503 cx.update(crate::init);
5504 let state = ListState::new(n, ListAlignment::Top, px(2048.)).measure_all();
5505 let probe = state.clone();
5506 let (_view, cx) = cx.add_window_view(|_w, _cx| ListRoot { state });
5507 let cx: &mut VisualTestContext = cx;
5508
5509 cx.run_until_parked();
5510 cx.update(|w, cx| {
5511 let _ = w.draw(cx);
5512 });
5513 cx.run_until_parked();
5514 cx.update(|w, cx| {
5515 let _ = w.draw(cx);
5516 });
5517
5518 let total = |p: &ListState| {
5519 f32::from(p.max_offset_for_scrollbar().y + p.viewport_bounds().size.height)
5520 };
5521 let mut totals = vec![total(&probe)];
5522 for _ in 0..20 {
5523 probe.scroll_by(px(150.));
5524 cx.update(|w, cx| {
5525 let _ = w.draw(cx);
5526 });
5527 cx.run_until_parked();
5528 totals.push(total(&probe));
5529 }
5530 let min = totals.iter().cloned().fold(f32::INFINITY, f32::min);
5531 let max = totals.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
5532 println!(
5533 "OUTER_LIST_PROBE min={min:.1} max={max:.1} delta={:.1}",
5534 max - min
5535 );
5536 assert!(
5537 (max - min) < 2.0,
5538 "list content total jittered while scrolling: min={min} max={max} totals={totals:?}"
5539 );
5540 }
5541}