Skip to main content

gpui_base/text/
text_view.rs

1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
5    AnyElement, App, Bounds, ClickEvent, ColorExt as _, ContentMask, Element, ElementId, Entity,
6    Global, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement,
7    IntoElement, LayoutId, MouseButton, ParentElement, Pixels, Refineable as _, SharedString,
8    StyleRefinement, Styled, Window, div, point, px,
9};
10
11use crate::text::TextViewFormat;
12use crate::text::markdown_ext::{MarkdownExtensions, MarkdownNode, MarkdownPlugin};
13use crate::text::node::{CodeBlock, TableData};
14use crate::text::range_highlight::{PendingReveal, RevealProgress};
15use crate::text::state::{LineSpan, SelectionFormat, TextViewState};
16use crate::text::stream_fade::TextViewMotion;
17use crate::{GlobalState, TextSelection, text::TextViewStyle};
18
19/// Type for code block actions generator function.
20pub(crate) type CodeBlockActionsFn =
21    dyn Fn(&CodeBlock, &mut Window, &mut App) -> AnyElement + Send + Sync;
22
23pub(crate) type CodeBlockHighlighterFn =
24    dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync;
25
26/// Application-wide defaults for TextViews that do not provide explicit
27/// presentation or syntax-highlighting overrides.
28#[derive(Clone, Default)]
29pub struct TextViewDefaults {
30    style: Option<TextViewStyle>,
31    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
32}
33
34impl Global for TextViewDefaults {}
35
36impl TextViewDefaults {
37    /// Creates defaults that leave every text view as Base renders it.
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Sets the style every text view starts from.
43    pub fn with_style(mut self, style: TextViewStyle) -> Self {
44        self.style = Some(style);
45        self
46    }
47
48    /// Sets the syntax highlighter used for fenced code blocks.
49    pub fn with_code_block_highlighter<F>(mut self, highlighter: F) -> Self
50    where
51        F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
52    {
53        self.code_block_highlighter = Some(Arc::new(highlighter));
54        self
55    }
56
57    /// Installs these defaults for the whole application.
58    pub fn install(self, cx: &mut App) {
59        cx.set_global(self);
60    }
61
62    /// Returns the installed defaults, or the Base ones when none were.
63    pub fn global(cx: &App) -> Self {
64        cx.try_global::<Self>().cloned().unwrap_or_default()
65    }
66
67    /// Whether a syntax highlighter was installed.
68    pub fn has_code_block_highlighter(&self) -> bool {
69        self.code_block_highlighter.is_some()
70    }
71}
72
73/// Type for the table actions generator function.
74pub(crate) type TableActionsFn =
75    dyn Fn(&TableData, &mut Window, &mut App) -> AnyElement + Send + Sync;
76
77pub(crate) type ImageSourceFn = dyn Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync;
78
79pub(crate) type LinkClickHandlerFn =
80    dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
81
82/// Kept by the element only, so unlike the handlers the state carries, it
83/// may hold a `ScrollHandle`.
84pub(crate) type RevealHandlerFn = dyn Fn(Bounds<Pixels>, &mut Window, &mut App);
85
86pub(crate) fn handle_link_click(
87    handler: &Option<Arc<LinkClickHandlerFn>>,
88    url: SharedString,
89    event: ClickEvent,
90    window: &mut Window,
91    cx: &mut App,
92) {
93    if let Some(handler) = handler {
94        handler(&url, &event, window, cx);
95    } else if match &event {
96        ClickEvent::Mouse(click) => {
97            matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
98        }
99        ClickEvent::Keyboard(_) => true,
100        ClickEvent::Touch(click) => !click.long_press,
101    } {
102        cx.open_url(&url);
103    }
104}
105
106/// A text view that can render Markdown or HTML.
107///
108/// ## Goals
109///
110/// - Provide a rich text rendering component for such as Markdown or HTML,
111/// used to display rich text in GPUI application (e.g., Help messages, Release notes)
112/// - Support Markdown GFM and HTML (Simple HTML like Safari Reader Mode) for showing most common used markups.
113/// - Support Heading, Paragraph, Bold, Italic, StrikeThrough, Code, Link, Image, Blockquote, List, Table, HorizontalRule, CodeBlock ...
114///
115/// ## Not Goals
116///
117/// - Customization of the complex style (some simple styles will be supported)
118/// - As a Markdown editor or viewer (If you want to like this, you must fork your version).
119/// - As a HTML viewer, we not support CSS, we only support basic HTML tags for used to as a content reader.
120///
121/// See also [`MarkdownElement`], [`HtmlElement`]
122#[derive(Clone)]
123pub struct TextView {
124    id: ElementId,
125    format: Option<TextViewFormat>,
126    text: Option<SharedString>,
127    pub(crate) state: Option<Entity<TextViewState>>,
128    text_view_style: Option<TextViewStyle>,
129    style: StyleRefinement,
130    selectable: bool,
131    selection_format: SelectionFormat,
132    scrollable: bool,
133    max_lines: Option<usize>,
134    code_block_actions: Option<Arc<CodeBlockActionsFn>>,
135    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
136    table_actions: Option<Arc<TableActionsFn>>,
137    link_click_handler: Option<Arc<LinkClickHandlerFn>>,
138    image_source: Option<Arc<ImageSourceFn>>,
139    reveal_handler: Option<Rc<RevealHandlerFn>>,
140    markdown_extensions: Arc<MarkdownExtensions>,
141    motion: Option<TextViewMotion>,
142}
143
144/// A plugin that can configure a [`TextView`].
145pub trait TextViewPlugin {
146    fn setup(self, text_view: TextView) -> TextView;
147}
148
149impl<P> TextViewPlugin for P
150where
151    P: MarkdownPlugin,
152{
153    fn setup(self, mut text_view: TextView) -> TextView {
154        let extensions = Arc::make_mut(&mut text_view.markdown_extensions);
155        let current = std::mem::take(extensions);
156        *extensions = current.plugin(self);
157        text_view
158    }
159}
160
161impl Styled for TextView {
162    fn style(&mut self) -> &mut StyleRefinement {
163        &mut self.style
164    }
165}
166
167impl TextView {
168    /// Create new TextView with managed state.
169    pub fn new(state: &Entity<TextViewState>) -> Self {
170        Self {
171            id: ElementId::Name(state.entity_id().to_string().into()),
172            state: Some(state.clone()),
173            format: None,
174            text: None,
175            text_view_style: None,
176            style: StyleRefinement::default(),
177            selectable: true,
178            selection_format: SelectionFormat::default(),
179            scrollable: false,
180            max_lines: None,
181            code_block_actions: None,
182            code_block_highlighter: None,
183            table_actions: None,
184            link_click_handler: None,
185            image_source: None,
186            reveal_handler: None,
187            markdown_extensions: Arc::default(),
188            motion: None,
189        }
190    }
191
192    /// Create a new markdown text view.
193    pub fn markdown(id: impl Into<ElementId>, markdown: impl Into<SharedString>) -> Self {
194        Self {
195            id: id.into(),
196            format: Some(TextViewFormat::Markdown),
197            text: Some(markdown.into()),
198            text_view_style: None,
199            style: StyleRefinement::default(),
200            state: None,
201            selectable: true,
202            selection_format: SelectionFormat::default(),
203            scrollable: false,
204            max_lines: None,
205            code_block_actions: None,
206            code_block_highlighter: None,
207            table_actions: None,
208            link_click_handler: None,
209            image_source: None,
210            reveal_handler: None,
211            markdown_extensions: Arc::default(),
212            motion: None,
213        }
214    }
215
216    /// Create a new html text view.
217    pub fn html(id: impl Into<ElementId>, html: impl Into<SharedString>) -> Self {
218        Self {
219            id: id.into(),
220            format: Some(TextViewFormat::Html),
221            text: Some(html.into()),
222            text_view_style: None,
223            style: StyleRefinement::default(),
224            state: None,
225            selectable: true,
226            selection_format: SelectionFormat::default(),
227            scrollable: false,
228            max_lines: None,
229            code_block_actions: None,
230            code_block_highlighter: None,
231            table_actions: None,
232            link_click_handler: None,
233            image_source: None,
234            reveal_handler: None,
235            markdown_extensions: Arc::default(),
236            motion: None,
237        }
238    }
239
240    /// Overrides the source of every document image, including embedded data URLs.
241    ///
242    /// Used for both rendering and intrinsic-size measurement. The returned source
243    /// is authoritative: pending or failed loads never fall back to the document URL.
244    /// Without this override, images use Base's default URI and data URL handling.
245    pub fn image_source<F>(mut self, resolver: F) -> Self
246    where
247        F: Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync + 'static,
248    {
249        self.image_source = Some(Arc::new(resolver));
250        self
251    }
252
253    /// Set [`TextViewStyle`].
254    pub fn style(mut self, style: TextViewStyle) -> Self {
255        self.text_view_style = Some(style);
256        self
257    }
258
259    /// Set whether the text view is selectable, default is true.
260    pub fn selectable(mut self, selectable: bool) -> Self {
261        self.selectable = selectable;
262        self
263    }
264
265    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
266    ///
267    /// With [`SelectionFormat::Source`], selecting inside `**bold**` yields
268    /// `**bold**` (the Markdown source) rather than `bold`.
269    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
270        self.selection_format = selection_format;
271        self
272    }
273
274    /// Set the text view to be scrollable, default is false.
275    ///
276    /// ## If true for `scrollable`
277    ///
278    /// The `scrollable` mode used for large content,
279    /// will show scrollbar, but requires the parent to have a fixed height,
280    /// and use [`gpui::list`] to render the content in a virtualized way.
281    ///
282    /// ## If false to fit content
283    ///
284    /// The TextView will expand to fit all content, no scrollbar.
285    /// This mode is suitable for small content, such as a few lines of text, a label, etc.
286    pub fn scrollable(mut self, scrollable: bool) -> Self {
287        self.scrollable = scrollable;
288        self
289    }
290
291    /// Clamp the rendered content to at most `n` lines of body text.
292    ///
293    /// The view's height is capped at `n` × the base line height, and a line
294    /// of glyphs is never cut in half: a line that would straddle the bottom
295    /// of the box is left out whole, across paragraphs, lists, headings, code
296    /// blocks and tables. Nothing is shown with less than a line of itself to
297    /// show, so the border and padding a table row leads with never strands at
298    /// the bottom; whatever has more than that is cut on the box edge and keeps
299    /// the part that fits, rather than disappearing and leaving blank space
300    /// behind.
301    ///
302    /// Check [`TextViewState::is_clamped`] (which answers for the frame that
303    /// was last painted) to decide whether to show an "expand" affordance.
304    ///
305    /// `n` counts lines of body text, so paragraph spacing and taller lines
306    /// mean fewer of them fit inside the capped height. A line taller than the
307    /// whole budget keeps the part that fits rather than emptying the box.
308    /// Ignored when [`Self::scrollable`] is set.
309    pub fn max_lines(mut self, max_lines: usize) -> Self {
310        self.max_lines = Some(max_lines);
311        self
312    }
313
314    /// Set custom block actions for code blocks.
315    ///
316    /// The closure receives the [`CodeBlock`],
317    /// and returns an element to display.
318    pub fn code_block_actions<F, E>(mut self, f: F) -> Self
319    where
320        F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
321        E: IntoElement,
322    {
323        self.code_block_actions = Some(Arc::new(move |code_block, window, cx| {
324            f(&code_block, window, cx).into_any_element()
325        }));
326        self
327    }
328
329    /// Adds opt-in syntax highlighting for fenced code blocks.
330    ///
331    /// Returned byte ranges are relative to [`CodeBlock::code`]. Invalid
332    /// ranges are discarded. Without this callback, code is unhighlighted.
333    pub fn code_block_highlighter<F>(mut self, highlighter: F) -> Self
334    where
335        F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
336    {
337        self.code_block_highlighter = Some(Arc::new(highlighter));
338        self
339    }
340
341    /// Like [`Self::code_block_highlighter`], with a highlighter that can be
342    /// handed to every frame.
343    ///
344    /// A code block reuses its highlights only while the highlighter is the
345    /// same `Arc`, so a view built every frame with a fresh closure
346    /// re-highlights every code block on every frame.
347    #[doc(hidden)]
348    pub fn shared_code_block_highlighter(
349        mut self,
350        highlighter: Arc<
351            dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync,
352        >,
353    ) -> Self {
354        self.code_block_highlighter = Some(highlighter);
355        self
356    }
357
358    /// Set custom actions to be rendered below each Markdown table.
359    ///
360    /// The closure receives the [`TableData`],
361    /// and returns an element to display.
362    pub fn table_actions<F, E>(mut self, f: F) -> Self
363    where
364        F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
365        E: IntoElement,
366    {
367        self.table_actions = Some(Arc::new(move |table, window, cx| {
368            f(table, window, cx).into_any_element()
369        }));
370        self
371    }
372
373    /// Handle pointer events on rendered links.
374    ///
375    /// The handler receives the resolved URL and the original GPUI click event.
376    /// Without a handler, links open through App::open_url.
377    pub fn on_link_click<F>(mut self, handler: F) -> Self
378    where
379        F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
380    {
381        self.link_click_handler = Some(Arc::new(handler));
382        self
383    }
384
385    /// Scroll a container that does not follow scroll requests to the line
386    /// of [`TextViewState::reveal_range`].
387    ///
388    /// A `gpui::list` scrolls to that line by itself; a `div` with
389    /// `overflow_y_scroll`, for one, does not. After a frame in which the
390    /// line was laid out but not visible, the handler receives its bounds in
391    /// window coordinates, to scroll the container, e.g. through its
392    /// `ScrollHandle`, until the line is visible.
393    pub fn on_reveal<F>(mut self, handler: F) -> Self
394    where
395        F: Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
396    {
397        self.reveal_handler = Some(Rc::new(handler));
398        self
399    }
400
401    /// Replace the Markdown extension registry.
402    pub fn markdown_extensions(mut self, extensions: MarkdownExtensions) -> Self {
403        self.markdown_extensions = Arc::new(extensions);
404        self
405    }
406
407    /// Set the motion policy; see [`TextViewMotion`]. Without one, the
408    /// state's own policy applies, which plays no motion by default.
409    pub fn motion(mut self, motion: TextViewMotion) -> Self {
410        self.motion = Some(motion);
411        self
412    }
413
414    /// Enable MDX JSX/expression parsing.
415    ///
416    /// This disables raw HTML parsing because `markdown-rs` gives HTML
417    /// priority over MDX when both are enabled.
418    pub fn markdown_mdx(mut self) -> Self {
419        let extensions = Arc::make_mut(&mut self.markdown_extensions);
420        *extensions = extensions.clone().mdx();
421        self
422    }
423
424    /// Register a custom block-level Markdown parser.
425    ///
426    /// The parser runs during Markdown AST conversion and must be independent
427    /// of [`Window`] / [`App`]. Store any parsed data in [`MarkdownNode`] and
428    /// render it later with [`Self::markdown_block_renderer`].
429    pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
430    where
431        F: for<'a> Fn(
432                &markdown::mdast::Node,
433                &crate::text::MarkdownParseContext<'a>,
434            ) -> Option<MarkdownNode>
435            + Send
436            + Sync
437            + 'static,
438    {
439        Arc::make_mut(&mut self.markdown_extensions).push_block_parser(parser);
440        self
441    }
442
443    /// Register a renderer for a custom block-level Markdown node name.
444    pub fn markdown_block_renderer<F, E>(
445        mut self,
446        name: impl Into<SharedString>,
447        renderer: F,
448    ) -> Self
449    where
450        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
451        E: IntoElement,
452    {
453        Arc::make_mut(&mut self.markdown_extensions).push_block_renderer(name, renderer);
454        self
455    }
456
457    /// Apply a reusable text view plugin.
458    pub fn plugin<P>(self, plugin: P) -> Self
459    where
460        P: TextViewPlugin,
461    {
462        plugin.setup(self)
463    }
464}
465
466impl IntoElement for TextView {
467    type Element = Self;
468
469    fn into_element(self) -> Self::Element {
470        self
471    }
472}
473
474pub struct TextViewLayoutState {
475    state: Entity<TextViewState>,
476    element: AnyElement,
477}
478
479pub struct TextViewPrepaintState {
480    hitbox: Hitbox,
481    /// Where paint has to pull the `max_lines` clip up to, because a glyph line
482    /// straddles the bottom of the box. `None` leaves the clip at the box edge,
483    /// where the container's hidden overflow already applies it.
484    clip_bottom: Option<Pixels>,
485    /// The touch handles this view owns, with their hitboxes.
486    touch_handles: crate::TouchHandleLayout,
487}
488
489/// Absorbs sub-pixel layout jitter: a line ending within a pixel of the box
490/// bottom counts as fitting inside it.
491const CLIP_EPSILON: Pixels = px(1.);
492
493/// The bottom of the last whole line at or above `y`, with the height of a line
494/// where it sits.
495fn last_line_bottom_above(spans: &[LineSpan], y: Pixels) -> Option<(Pixels, Pixels)> {
496    let mut last: Option<(Pixels, Pixels)> = None;
497    let mut keep = |bottom: Pixels, line_height: Pixels| {
498        if bottom <= y + CLIP_EPSILON && last.is_none_or(|(last, _)| bottom > last) {
499            last = Some((bottom, line_height));
500        }
501    };
502
503    for span in spans {
504        if span.line_height <= px(0.) {
505            continue;
506        }
507        let mut bottom = span.top + span.line_height;
508        while bottom <= span.bottom + CLIP_EPSILON {
509            keep(bottom, span.line_height);
510            bottom += span.line_height;
511        }
512        // The span's own bottom covers a last line taller than the rest.
513        keep(span.bottom, span.line_height);
514    }
515
516    last
517}
518
519/// Where to clip, given the lines a descendant `Inline` reported. `None` leaves
520/// the clip on the box edge.
521///
522/// Two things are never shown: half a line of glyphs, and anything with less
523/// than a line of itself to show. A line straddling `box_bottom` is left out
524/// whole, and so is the strip between it and the line before — the border and
525/// padding a table row leads with reads as a rendering fault rather than as a
526/// row. Whatever has more than a line to show is cut on the edge and keeps the
527/// part that fits, so the box holds no blank space it could have filled.
528fn line_safe_clip_bottom(
529    spans: &[LineSpan],
530    box_bottom: Pixels,
531    content_bottom: Pixels,
532) -> Option<Pixels> {
533    let mut clip = box_bottom;
534
535    for span in spans {
536        if span.line_height <= px(0.)
537            || span.top >= box_bottom
538            || span.bottom <= box_bottom + CLIP_EPSILON
539        {
540            continue;
541        }
542        let whole_lines = ((box_bottom - span.top) / span.line_height).floor();
543        let line_top = span.top + span.line_height * whole_lines;
544        // A line starting on the box edge is not straddling it.
545        if line_top < box_bottom - CLIP_EPSILON {
546            clip = clip.min(line_top);
547        }
548    }
549
550    let Some((last_line_bottom, line_height)) = last_line_bottom_above(spans, clip) else {
551        // Leaving the straddling line out would leave nothing at all — a first
552        // line taller than the whole budget, a heading in a one-line box. It
553        // keeps the part that fits instead, because an empty clamp reads as
554        // broken where a cut one reads as more to come.
555        return None;
556    };
557
558    // Snap away a scrap. Only content that continues past the box can leave
559    // one: the space under the last line of a document that fits is the box's
560    // own, not a piece of something below.
561    if content_bottom > box_bottom + CLIP_EPSILON {
562        let strip = clip - last_line_bottom;
563        if strip > CLIP_EPSILON && strip < line_height {
564            clip = last_line_bottom;
565        }
566    }
567
568    (clip < box_bottom - CLIP_EPSILON).then_some(clip)
569}
570
571impl Element for TextView {
572    type RequestLayoutState = TextViewLayoutState;
573    type PrepaintState = TextViewPrepaintState;
574
575    fn id(&self) -> Option<ElementId> {
576        Some(self.id.clone())
577    }
578
579    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
580        None
581    }
582
583    fn request_layout(
584        &mut self,
585        _: Option<&GlobalElementId>,
586        _: Option<&InspectorElementId>,
587        window: &mut Window,
588        cx: &mut App,
589    ) -> (LayoutId, Self::RequestLayoutState) {
590        let state = if let Some(state) = self.state.clone() {
591            state
592        } else {
593            let default_format = self.format.unwrap_or(TextViewFormat::Markdown);
594            let default_text = self.text.clone().unwrap_or_default();
595
596            let state = window.use_keyed_state(
597                SharedString::from(format!("{}/state", self.id)),
598                cx,
599                move |_, cx| {
600                    if default_format == TextViewFormat::Markdown {
601                        TextViewState::markdown(default_text.as_str(), cx)
602                    } else {
603                        TextViewState::html(default_text.as_str(), cx)
604                    }
605                },
606            );
607            self.state = Some(state.clone());
608            state
609        };
610
611        // `max_lines` needs the whole document laid out to snap the clip to a
612        // whole line, so it only applies to the fit-content mode.
613        let max_lines = self.max_lines.filter(|_| !self.scrollable);
614
615        // Resolve the style by reference: this runs every frame, and the
616        // style only reaches the state when it changed.
617        let defaults = cx.try_global::<TextViewDefaults>();
618        let theme_style;
619        let text_view_style = match (
620            &self.text_view_style,
621            defaults.and_then(|d| d.style.as_ref()),
622        ) {
623            (Some(style), _) | (None, Some(style)) => style,
624            (None, None) => {
625                theme_style = TextViewStyle::from_theme(&crate::Theme::global(cx));
626                &theme_style
627            }
628        };
629        let foreground = text_view_style.foreground();
630        let text_view_style = (*state.read(cx).text_view_style != *text_view_style)
631            .then(|| Arc::new(text_view_style.clone()));
632        let code_block_highlighter = self
633            .code_block_highlighter
634            .clone()
635            .or_else(|| defaults.and_then(|d| d.code_block_highlighter.clone()));
636
637        state.update(cx, |state, cx| {
638            state.code_block_actions = self.code_block_actions.clone();
639            state.code_block_highlighter = code_block_highlighter;
640            state.table_actions = self.table_actions.clone();
641            state.link_click_handler = self.link_click_handler.clone();
642            state.image_source = self.image_source.clone();
643            state.set_markdown_extensions(self.markdown_extensions.clone(), cx);
644            if let Some(motion) = &self.motion {
645                state.set_motion(motion.clone());
646            }
647            state.selectable = self.selectable;
648            state.selection_format = self.selection_format;
649            state.scrollable = self.scrollable;
650            state.max_lines = max_lines;
651            if let Some(text_view_style) = text_view_style {
652                state.selection_revision = state.selection_revision.wrapping_add(1);
653                state.text_view_style = text_view_style;
654            }
655
656            if let Some(text) = &self.text {
657                state.set_element_text(text, cx);
658            }
659        });
660
661        let focus_handle = state.read(cx).focus_handle.clone();
662        let list_state = state.read(cx).list_state.clone();
663        // Cap the box at `n` body-text lines (the effective text style may be
664        // refined by this view's own style, e.g. `.text_sm()`); hidden
665        // overflow also clips descendant hitboxes to the box during prepaint.
666        let max_lines_cap = max_lines.map(|max_lines| {
667            let mut text_style = window.text_style();
668            text_style.refine(&self.style.text);
669            text_style.line_height_in_pixels(window.rem_size()) * max_lines as f32
670        });
671
672        let mut el = div()
673            .id(("text-view-scroll", state.entity_id()))
674            .key_context("TextView")
675            .track_focus(&focus_handle)
676            .when(self.scrollable, |this| this.size_full())
677            .when_some(max_lines_cap, |this, cap| this.max_h(cap).overflow_hidden())
678            .relative()
679            .text_color(foreground)
680            .on_action(move |_: &crate::input::Copy, window, cx| {
681                let text = TextSelection::selected_text(window, cx).trim().to_string();
682                if text.is_empty() {
683                    cx.propagate();
684                    return;
685                }
686                cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
687            })
688            .on_action(window.listener_for(&state, TextViewState::on_action_select_all))
689            .child(state.clone())
690            // Overlay controls must paint after the document, otherwise rich
691            // content and selection backgrounds cover the thumb and hitbox.
692            .when(self.scrollable, |this| {
693                this.child(
694                    div().absolute().inset_0().child(
695                        crate::Scrollbar::vertical(&list_state)
696                            .id(("text-view-scrollbar", state.entity_id()))
697                            .viewport_from_layout(),
698                    ),
699                )
700            })
701            .refine_style(&self.style)
702            .into_any_element();
703        let layout_id = el.request_layout(window, cx);
704        (layout_id, TextViewLayoutState { state, element: el })
705    }
706
707    fn prepaint(
708        &mut self,
709        _: Option<&GlobalElementId>,
710        _: Option<&InspectorElementId>,
711        bounds: Bounds<Pixels>,
712        request_layout: &mut Self::RequestLayoutState,
713        window: &mut Window,
714        cx: &mut App,
715    ) -> Self::PrepaintState {
716        let state = request_layout.state.clone();
717        let max_lines_active = state.read(cx).max_lines.is_some();
718        if max_lines_active {
719            if let Ok(mut line_spans) = state.read(cx).line_spans.lock() {
720                line_spans.clear();
721            }
722            // Descendant `Inline`s report their line spans through the state
723            // stack during prepaint (in addition to the paint-time push below).
724            GlobalState::global_mut(cx)
725                .text_view_state_stack
726                .push(state.clone());
727        }
728        request_layout.element.prepaint(window, cx);
729        if max_lines_active {
730            GlobalState::global_mut(cx).text_view_state_stack.pop();
731        }
732
733        let mut clip_bottom = None;
734        if max_lines_active {
735            let (line_spans, content_bottom) = {
736                let state = state.read(cx);
737                (
738                    state
739                        .line_spans
740                        .lock()
741                        .map(|spans| spans.clone())
742                        .unwrap_or_default(),
743                    state.bounds().bottom(),
744                )
745            };
746            // The content keeps its natural height inside the capped box, so
747            // this sees everything the box cannot show — including a tall image
748            // that reports no lines of its own.
749            let clipped = content_bottom > bounds.bottom() + px(1.);
750            // Notify on change so observers (e.g. an "expand" button gated on
751            // `is_clamped`) re-render once the flag flips.
752            if state.read(cx).clamped != clipped {
753                state.update(cx, |state, cx| {
754                    state.clamped = clipped;
755                    cx.notify();
756                });
757            }
758            if clipped {
759                clip_bottom = line_safe_clip_bottom(&line_spans, bounds.bottom(), content_bottom);
760            }
761        }
762
763        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
764        // Over the text, so after its hitbox.
765        let touch_handles = if self.selectable {
766            state
767                .read(cx)
768                .selection_adapter
769                .prepaint_touch_handles(window, cx)
770        } else {
771            crate::TouchHandleLayout::default()
772        };
773        TextViewPrepaintState {
774            hitbox,
775            clip_bottom,
776            touch_handles,
777        }
778    }
779
780    fn paint(
781        &mut self,
782        _: Option<&GlobalElementId>,
783        _: Option<&InspectorElementId>,
784        bounds: Bounds<Pixels>,
785        request_layout: &mut Self::RequestLayoutState,
786        prepaint: &mut Self::PrepaintState,
787        window: &mut Window,
788        cx: &mut App,
789    ) {
790        let state = &request_layout.state;
791        if self.selectable {
792            state.update(cx, |state, _| state.selection_adapter.begin_frame());
793        }
794
795        GlobalState::global_mut(cx)
796            .text_view_state_stack
797            .push(state.clone());
798        if let Some(clip_bottom) = prepaint.clip_bottom {
799            // Snap the `max_lines` clip to the last whole line that fits, so a
800            // line of glyphs is never cut in half.
801            let mask = ContentMask {
802                fade_out: Default::default(),
803                bounds: Bounds::from_corners(bounds.origin, point(bounds.right(), clip_bottom)),
804            };
805            window.with_content_mask(Some(mask), |window| {
806                request_layout.element.paint(window, cx);
807            });
808        } else {
809            request_layout.element.paint(window, cx);
810        }
811        GlobalState::global_mut(cx).text_view_state_stack.pop();
812
813        // Every list has scrolled by now, so the line of a reveal is where
814        // it ends up this frame.
815        if state.read(cx).pending_reveal.is_some() {
816            let progress = state.update(cx, |state, _| {
817                state.pending_reveal.as_mut().map(PendingReveal::progress)
818            });
819            match progress {
820                Some(RevealProgress::Shown) => {
821                    state.update(cx, |state, _| state.pending_reveal = None);
822                }
823                Some(RevealProgress::Hidden(line)) => {
824                    if let Some(handler) = &self.reveal_handler {
825                        handler(line, window, cx);
826                    }
827                }
828                Some(RevealProgress::NotLaidOut) | None => {}
829            }
830        }
831
832        if self.selectable {
833            let (adapter, scroll_offset, content_bounds, self_scroll, handle_color) = {
834                let state = state.read(cx);
835                (
836                    state.selection_adapter.clone(),
837                    state.scroll_offset(),
838                    state.bounds(),
839                    state.scrollable,
840                    state.text_view_style.selection().opacity(1.),
841                )
842            };
843            let document_order = GlobalState::global_mut(cx).next_selection_document_order();
844            adapter.register(
845                prepaint.hitbox.clone(),
846                content_bounds,
847                scroll_offset,
848                document_order,
849                self_scroll,
850                window,
851                cx,
852            );
853            // The handles of a touch selection go over the text, and under
854            // whatever is painted over the text after it.
855            adapter.paint_touch_handles(&prepaint.touch_handles, handle_color, window, cx);
856        }
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    use std::sync::{
863        Arc,
864        atomic::{AtomicUsize, Ordering},
865    };
866
867    use super::{TextView, TextViewPlugin};
868    use crate::text::{TableData, TextViewState, TextViewStyle};
869    use gpui::{
870        AppContext as _, Bounds, ClickEvent, Context, Entity, InteractiveElement as _, IntoElement,
871        Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Overflow, ParentElement as _, Pixels,
872        Render, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
873        TestAppContext, VisualTestContext, Window, div, point, px, rems,
874    };
875
876    struct TextViewTestRoot {
877        text_view: Entity<TextViewState>,
878    }
879
880    struct InlineHoverTestRoot {
881        view: Entity<TextViewState>,
882        builds: Arc<AtomicUsize>,
883        format: crate::text::SelectionFormat,
884    }
885
886    struct InlineHoverCard;
887    impl Render for InlineHoverCard {
888        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
889            div()
890                .debug_selector(|| "inline-test-card".into())
891                .w(px(120.))
892                .h(px(40.))
893                .child("Member profile")
894        }
895    }
896
897    impl Render for InlineHoverTestRoot {
898        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
899            let builds = self.builds.clone();
900            div()
901                .pl(px(150.))
902                .w(px(300.))
903                .text_size(px(16.))
904                .child(crate::TextSelectionLayer)
905                .child(
906                    TextView::new(&self.view)
907                        .selection_format(self.format)
908                        .plugin(
909                            crate::text::markdown_ext::TestInlinePlugin::new("mention")
910                                .parse_with(|node, _| {
911                                    let markdown::mdast::Node::Link(link) = node else {
912                                        return None;
913                                    };
914                                    let handle = link.url.strip_prefix("mention:")?;
915                                    Some(
916                                        crate::text::MarkdownNode::new("mention", ())
917                                            .text(format!("@{handle}")),
918                                    )
919                                })
920                                .render_with(move |_, _, _, _| {
921                                    let builds = builds.clone();
922                                    Some(crate::text::InlineElement::new(
923                                        crate::HoverCard::new("mention-hover")
924                                            .anchor(gpui::Anchor::TopCenter)
925                                            .trigger(div().child("@member"))
926                                            .content(move |_, _, cx| {
927                                                builds.fetch_add(1, Ordering::Relaxed);
928                                                div()
929                                                    .id("hover-content")
930                                                    .child(cx.new(|_| InlineHoverCard))
931                                            }),
932                                    ))
933                                }),
934                        ),
935                )
936        }
937    }
938
939    #[gpui::test]
940    fn inline_plugin_reuses_render_and_preserves_native_child_events(cx: &mut TestAppContext) {
941        use std::sync::Mutex;
942        struct ControlPlugin(Arc<Mutex<Vec<String>>>);
943        impl crate::text::MarkdownPlugin for ControlPlugin {
944            fn name(&self) -> &str {
945                "control"
946            }
947            fn parse(
948                &self,
949                node: &markdown::mdast::Node,
950                _: &crate::text::MarkdownParseContext<'_>,
951            ) -> Option<crate::text::MarkdownNode> {
952                let markdown::mdast::Node::Link(link) = node else {
953                    return None;
954                };
955                let label = link.url.strip_prefix("control:")?;
956                Some(crate::text::MarkdownNode::new("control", ()).text(label.to_string()))
957            }
958            fn render(
959                &self,
960                node: &crate::text::MarkdownNode,
961                _: &mut Window,
962                _: &mut gpui::App,
963            ) -> impl IntoElement {
964                let clicks = self.0.clone();
965                let label = node.as_text().to_string();
966                div()
967                    .id("same-control-id")
968                    .w(px(60.))
969                    .h(px(24.))
970                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
971                    .on_click(move |_, _, _| clicks.lock().unwrap().push(label.clone()))
972                    .child(node.as_text().to_string())
973            }
974        }
975        struct Root {
976            view: Entity<TextViewState>,
977            clicks: Arc<Mutex<Vec<String>>>,
978        }
979        impl Render for Root {
980            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
981                div()
982                    .w(px(300.))
983                    .child(crate::TextSelectionLayer)
984                    .child(TextView::new(&self.view).plugin(ControlPlugin(self.clicks.clone())))
985            }
986        }
987        cx.update(crate::init);
988        let clicks = Arc::new(Mutex::new(Vec::new()));
989        let captured = clicks.clone();
990        let (root, cx) = cx.add_window_view(move |_, cx| Root {
991            view: cx.new(|cx| TextViewState::markdown("[one](control:one)[two](control:two)", cx)),
992            clicks,
993        });
994        cx.run_until_parked();
995        cx.update(|window, cx| {
996            window.draw(cx).clear(cx);
997        });
998        let bounds = root.read_with(cx, |root, cx| {
999            root.view.read(cx).selection_adapter.text_bounds()
1000        });
1001        assert_eq!(bounds.len(), 2);
1002        for bounds in bounds {
1003            cx.simulate_click(bounds.center(), Modifiers::default());
1004            cx.update(|window, cx| {
1005                window.draw(cx).clear(cx);
1006            });
1007        }
1008        assert_eq!(*captured.lock().unwrap(), vec!["one", "two"]);
1009    }
1010
1011    #[gpui::test]
1012    fn inline_hover_card_is_lazy_and_retains_atomic_copy(cx: &mut TestAppContext) {
1013        cx.update(crate::init);
1014        let builds = Arc::new(AtomicUsize::new(0));
1015        let source = "[@member](mention:member)";
1016        let (root, cx) = cx.add_window_view(|_, cx| InlineHoverTestRoot {
1017            view: cx.new(|cx| TextViewState::markdown(source, cx)),
1018            builds: builds.clone(),
1019            format: crate::text::SelectionFormat::Plain,
1020        });
1021        cx.run_until_parked();
1022        cx.update(|window, cx| window.draw(cx).clear(cx));
1023        assert_eq!(builds.load(Ordering::Relaxed), 0);
1024        let view = root.read_with(cx, |root, _| root.view.clone());
1025        let bounds = view.read_with(cx, |view, _| view.selection_adapter.text_bounds()[0]);
1026        cx.update(|window, cx| {
1027            window.simulate_mouse_move(point(bounds.right() - px(1.), bounds.center().y), cx)
1028        });
1029        cx.run_until_parked();
1030        cx.executor()
1031            .advance_clock(std::time::Duration::from_secs(1));
1032        cx.run_until_parked();
1033        cx.update(|window, cx| window.draw(cx).clear(cx));
1034        assert!(
1035            builds.load(Ordering::Relaxed) > 0,
1036            "hover did not build the card"
1037        );
1038        cx.update(|window, cx| window.draw(cx).clear(cx));
1039        let card = cx
1040            .debug_bounds("inline-test-card")
1041            .expect("hover card should be painted");
1042        assert!(
1043            (card.center().x - bounds.center().x).abs() < px(1.),
1044            "card {card:?} must be centered on mention {bounds:?}"
1045        );
1046        assert!(
1047            card.top() >= bounds.bottom(),
1048            "card should be below the mention"
1049        );
1050        for (format, expected) in [
1051            (crate::text::SelectionFormat::Plain, "@member"),
1052            (crate::text::SelectionFormat::Source, source),
1053        ] {
1054            root.update(cx, |root, cx| {
1055                root.format = format;
1056                cx.notify();
1057            });
1058            view.update(cx, |view, cx| {
1059                view.set_selection_format(format, cx);
1060                view.select_all(cx);
1061            });
1062            cx.update(|window, cx| window.draw(cx).clear(cx));
1063            assert_eq!(
1064                view.read_with(cx, |view, _| view.selected_text()).trim(),
1065                expected
1066            );
1067        }
1068    }
1069
1070    struct InlinePluginTestRoot {
1071        text_view: Entity<TextViewState>,
1072        width: Pixels,
1073        font_size: Pixels,
1074        source_format: bool,
1075        prepared_size: Option<Arc<AtomicUsize>>,
1076    }
1077
1078    impl Render for InlinePluginTestRoot {
1079        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1080            let prepared_size = self.prepared_size.clone();
1081            div().w(self.width).text_size(self.font_size).child(crate::TextSelectionLayer).child(
1082                TextView::new(&self.text_view)
1083                    .selection_format(if self.source_format { crate::text::SelectionFormat::Source }
1084                        else { crate::text::SelectionFormat::Plain })
1085
1086                    .plugin(crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(|node, _| {
1087                        let markdown::mdast::Node::InlineMath(math) = node else { return None };
1088                        Some(crate::text::MarkdownNode::new("math", ()).text(format!("{}²", math.value)))
1089                    }).render_with(move |_, context, _, _| {
1090                        let value = prepared_size.as_ref()?.load(Ordering::Relaxed) as f32;
1091                        let image = Arc::new(gpui::Image::from_bytes(gpui::ImageFormat::Svg,
1092                            b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"40\"><path d=\"M0 0L40 40\" stroke=\"black\"/></svg>".to_vec()));
1093                        let unit = context.font_size() / 16.;
1094                        Some(crate::text::InlineElement::new(gpui::img(image).w(unit * value).h(unit * value)).with_baseline(unit * value * 0.75))
1095                    })))
1096        }
1097    }
1098
1099    #[gpui::test]
1100    fn inline_plugins_drag_and_copy_across_formulas_in_both_directions(cx: &mut TestAppContext) {
1101        cx.update(crate::init);
1102        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1103            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1104            width: px(420.),
1105            font_size: px(16.),
1106            source_format: false,
1107            prepared_size: None,
1108        });
1109        let cx: &mut VisualTestContext = cx;
1110        for font_size in [16., 24., 32.] {
1111            for width in [60., 160., 420.] {
1112                for prepared in [None, Some(32)] {
1113                    for source_format in [false, true] {
1114                        root.update(cx, |root, cx| {
1115                            root.source_format = source_format;
1116                            root.width = px(width);
1117                            root.font_size = px(font_size);
1118                            root.prepared_size =
1119                                prepared.map(|value| Arc::new(AtomicUsize::new(value)));
1120                            cx.notify();
1121                        });
1122                        cx.run_until_parked();
1123                        cx.update(|window, cx| window.draw(cx).clear(cx));
1124                        let bounds =
1125                            root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1126                        let text_bounds = root.read_with(cx, |root, cx| {
1127                            root.text_view.read(cx).selection_adapter.text_bounds()
1128                        });
1129                        let first = text_bounds.first().unwrap();
1130                        let last = text_bounds.last().unwrap();
1131                        let left =
1132                            point(first.left() + px(0.1), first.top() + first.size.height / 2.);
1133                        let right =
1134                            point(last.right() - px(0.1), last.top() + last.size.height / 2.);
1135                        for (start, end) in [(left, right), (right, left)] {
1136                            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1137                            cx.update(|window, cx| window.draw(cx).clear(cx));
1138                            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1139                            cx.update(|window, cx| window.draw(cx).clear(cx));
1140                            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1141                            cx.update(|window, cx| window.draw(cx).clear(cx));
1142                            let selected = root
1143                                .read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1144                            assert_eq!(
1145                                selected.trim(),
1146                                if source_format {
1147                                    "中文 $x$ $y$ English"
1148                                } else {
1149                                    "中文 x² y² English"
1150                                },
1151                                "start={start:?} end={end:?} bounds={bounds:?} width={width} font_size={font_size} prepared={prepared:?}"
1152                            );
1153                        }
1154                    }
1155                }
1156            }
1157        }
1158    }
1159
1160    #[gpui::test]
1161    fn inline_resource_size_update_reflows_without_changing_selection(cx: &mut TestAppContext) {
1162        cx.update(crate::init);
1163        let prepared_size = Arc::new(AtomicUsize::new(16));
1164        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1165            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1166            width: px(160.),
1167            font_size: px(16.),
1168            source_format: false,
1169            prepared_size: Some(prepared_size.clone()),
1170        });
1171        let cx: &mut VisualTestContext = cx;
1172        cx.run_until_parked();
1173        cx.update(|window, cx| window.draw(cx).clear(cx));
1174        let before = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1175        let regions = root.read_with(cx, |root, cx| {
1176            root.text_view.read(cx).selection_adapter.text_bounds()
1177        });
1178        let first = regions.first().unwrap();
1179        let last = regions.last().unwrap();
1180        let start = point(first.left() + px(0.1), first.top() + px(10.));
1181        let end = point(last.right() - px(0.1), last.top() + px(10.));
1182        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1183        cx.update(|window, cx| window.draw(cx).clear(cx));
1184        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1185        cx.update(|window, cx| window.draw(cx).clear(cx));
1186        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1187        cx.update(|window, cx| window.draw(cx).clear(cx));
1188        assert_eq!(
1189            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1190                .trim(),
1191            "中文 x² y² English"
1192        );
1193        prepared_size.store(100, Ordering::Relaxed);
1194        root.update(cx, |root, cx| {
1195            root.text_view
1196                .update(cx, |state, cx| state.invalidate_inline_layout(cx))
1197        });
1198        cx.run_until_parked();
1199        cx.update(|window, cx| window.draw(cx).clear(cx));
1200        let after = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1201        assert!(after.size.height > before.size.height * 2.);
1202        assert_eq!(
1203            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1204                .trim(),
1205            "中文 x² y² English"
1206        );
1207    }
1208
1209    #[gpui::test]
1210    fn triple_click_on_formula_selects_its_entire_mixed_line(cx: &mut TestAppContext) {
1211        cx.update(crate::init);
1212        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1213            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1214            width: px(420.),
1215            font_size: px(16.),
1216            source_format: false,
1217            prepared_size: None,
1218        });
1219        let cx: &mut VisualTestContext = cx;
1220        cx.run_until_parked();
1221        cx.update(|window, cx| window.draw(cx).clear(cx));
1222        let regions = root.read_with(cx, |root, cx| {
1223            root.text_view.read(cx).selection_adapter.text_bounds()
1224        });
1225        let formula = regions[1];
1226        let position = formula.center();
1227        cx.simulate_event(MouseDownEvent {
1228            position,
1229            modifiers: Modifiers::default(),
1230            button: MouseButton::Left,
1231            click_count: 3,
1232            first_mouse: false,
1233        });
1234        cx.simulate_event(MouseUpEvent {
1235            position,
1236            modifiers: Modifiers::default(),
1237            button: MouseButton::Left,
1238            click_count: 3,
1239        });
1240        cx.update(|window, cx| window.draw(cx).clear(cx));
1241        assert_eq!(
1242            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1243                .trim(),
1244            "before x² after"
1245        );
1246        root.update(cx, |root, cx| {
1247            root.source_format = true;
1248            cx.notify();
1249        });
1250        cx.update(|window, cx| window.draw(cx).clear(cx));
1251        assert_eq!(
1252            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1253                .trim(),
1254            "before $x$ after"
1255        );
1256    }
1257
1258    #[gpui::test]
1259    fn double_click_on_formula_selects_only_that_object(cx: &mut TestAppContext) {
1260        cx.update(crate::init);
1261        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1262            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1263            width: px(420.),
1264            font_size: px(16.),
1265            source_format: false,
1266            prepared_size: None,
1267        });
1268        let cx: &mut VisualTestContext = cx;
1269        cx.run_until_parked();
1270        cx.update(|window, cx| window.draw(cx).clear(cx));
1271        let regions = root.read_with(cx, |root, cx| {
1272            root.text_view.read(cx).selection_adapter.text_bounds()
1273        });
1274        let position = regions[1].center();
1275        cx.simulate_event(MouseDownEvent {
1276            position,
1277            modifiers: Modifiers::default(),
1278            button: MouseButton::Left,
1279            click_count: 2,
1280            first_mouse: false,
1281        });
1282        cx.simulate_event(MouseUpEvent {
1283            position,
1284            modifiers: Modifiers::default(),
1285            button: MouseButton::Left,
1286            click_count: 2,
1287        });
1288        cx.update(|window, cx| window.draw(cx).clear(cx));
1289        // Two clicks stop at the object; only three take the whole line.
1290        assert_eq!(
1291            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1292                .trim(),
1293            "x²"
1294        );
1295    }
1296
1297    /// A scrollable viewport, so the list has a bounded height to measure
1298    /// against and `max_offset_for_scrollbar` reports a real scroll extent.
1299    struct ScrollExtentTestRoot {
1300        text_view: Entity<TextViewState>,
1301    }
1302
1303    impl Render for ScrollExtentTestRoot {
1304        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1305            div()
1306                .w(px(400.))
1307                .h(px(200.))
1308                .overflow_hidden()
1309                .child(TextView::new(&self.text_view).scrollable(true))
1310        }
1311    }
1312
1313    /// `count` paragraphs, each `words` words long, so two documents can share
1314    /// a block count while differing wildly in height.
1315    fn document_of(count: usize, words: usize) -> String {
1316        (1..=count)
1317            .map(|i| format!("Block {i}: {}", "lorem ipsum dolor ".repeat(words)))
1318            .collect::<Vec<_>>()
1319            .join("\n\n")
1320    }
1321
1322    /// Replacing a document with one that happens to have the *same* block
1323    /// count must still re-measure. `Document::render_root` only resets the
1324    /// list when the count changes, so without an explicit re-measure every
1325    /// cached height stays with the previous document and the scroll extent
1326    /// keeps describing it.
1327    #[gpui::test]
1328    fn replacing_a_document_with_an_equal_block_count_remeasures(cx: &mut TestAppContext) {
1329        crate::test_text_system::install(cx);
1330        cx.update(crate::init);
1331
1332        const BLOCKS: usize = 24;
1333        let short = document_of(BLOCKS, 1);
1334        let tall = document_of(BLOCKS, 60);
1335
1336        let (root, cx) = cx.add_window_view(|_, cx| ScrollExtentTestRoot {
1337            text_view: cx.new(|cx| TextViewState::markdown(&short, cx)),
1338        });
1339        let cx: &mut VisualTestContext = cx;
1340        cx.simulate_resize(gpui::size(px(400.), px(200.)));
1341
1342        // The list is populated and measured during layout, so every
1343        // assertion below has to follow a real frame.
1344        let settle = |cx: &mut VisualTestContext| {
1345            cx.run_until_parked();
1346            cx.update(|window, cx| window.draw(cx).clear(cx));
1347            cx.run_until_parked();
1348        };
1349        settle(cx);
1350
1351        let scroll_extent = |cx: &mut VisualTestContext| {
1352            root.read_with(cx, |root, cx| {
1353                root.text_view
1354                    .read(cx)
1355                    .list_state()
1356                    .max_offset_for_scrollbar()
1357                    .y
1358            })
1359        };
1360
1361        let short_extent = scroll_extent(cx);
1362
1363        root.update(cx, |root, cx| {
1364            root.text_view
1365                .update(cx, |state, cx| state.set_text(&tall, cx));
1366        });
1367        settle(cx);
1368
1369        root.read_with(cx, |root, cx| {
1370            assert_eq!(
1371                root.text_view.read(cx).list_state().item_count(),
1372                BLOCKS,
1373                "the replacement must keep the block count, or the list resets and the bug cannot occur"
1374            );
1375        });
1376
1377        let tall_extent = scroll_extent(cx);
1378        assert!(
1379            tall_extent > short_extent * 5.,
1380            "a much taller document must grow the scroll extent, but it went from \
1381             {short_extent:?} to {tall_extent:?}"
1382        );
1383    }
1384
1385    struct StatelessMarkdownRoot {
1386        renders: Arc<AtomicUsize>,
1387    }
1388
1389    impl Render for StatelessMarkdownRoot {
1390        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1391            self.renders.fetch_add(1, Ordering::Relaxed);
1392            div().child(
1393                TextView::markdown("stateless-markdown", include_str!("../../../../README.md"))
1394                    .markdown_block_parser(|_, _| None),
1395            )
1396        }
1397    }
1398
1399    struct DummyTextViewPlugin;
1400
1401    impl TextViewPlugin for DummyTextViewPlugin {
1402        fn setup(self, mut text_view: TextView) -> TextView {
1403            text_view.selectable = true;
1404            text_view
1405        }
1406    }
1407
1408    #[gpui::test]
1409    fn text_view_constructors_are_selectable_by_default(cx: &mut TestAppContext) {
1410        cx.update(crate::init);
1411        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1412
1413        assert!(TextView::new(&state).selectable);
1414        assert!(TextView::markdown("markdown", "text").selectable);
1415        assert!(TextView::html("html", "<p>text</p>").selectable);
1416    }
1417
1418    #[gpui::test]
1419    fn stateless_markdown_with_rebuilt_parser_settles(cx: &mut TestAppContext) {
1420        cx.update(crate::init);
1421        let renders = Arc::new(AtomicUsize::new(0));
1422        let (_, cx) = cx.add_window_view({
1423            let renders = renders.clone();
1424            move |_, _| StatelessMarkdownRoot { renders }
1425        });
1426        let cx: &mut VisualTestContext = cx;
1427
1428        cx.run_until_parked();
1429        cx.update(|window, cx| window.draw(cx).clear(cx));
1430        let renders_after_redraw = renders.load(Ordering::Relaxed);
1431        cx.run_until_parked();
1432        assert_eq!(
1433            renders.load(Ordering::Relaxed),
1434            renders_after_redraw,
1435            "an unchanged TextView must not schedule another render after its parser is rebuilt",
1436        );
1437    }
1438
1439    #[gpui::test]
1440    fn markdown_data_url_image_is_decoded_inline(cx: &mut TestAppContext) {
1441        use gpui::{Image, ImageFormat, ImageSource};
1442
1443        // A 1x1 red PNG.
1444        const PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
1445
1446        cx.update(crate::init);
1447        let markdown = format!("Inline ![dot](data:image/png;base64,{PNG_BASE64}) image");
1448        let (_, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new(&markdown, cx));
1449        let cx: &mut VisualTestContext = cx;
1450
1451        cx.run_until_parked();
1452        cx.update(|window, cx| window.draw(cx).clear(cx));
1453
1454        // `Image` keys the asset system by a hash of its bytes, so rebuilding it
1455        // from the same body finds the entry the text view's `img` registered
1456        // when it rendered — proof the body was decoded in place instead of
1457        // being fetched over HTTP.
1458        let bytes = data_url::DataUrl::process(&format!("data:image/png;base64,{PNG_BASE64}"))
1459            .unwrap()
1460            .decode_to_vec()
1461            .unwrap()
1462            .0;
1463        let image = Arc::new(Image::from_bytes(ImageFormat::Png, bytes));
1464        assert!(
1465            cx.update(|_, cx| ImageSource::Image(image).is_asset_cached(cx)),
1466            "the data URL image must be handed to GPUI as decoded bytes",
1467        );
1468    }
1469
1470    #[gpui::test]
1471    fn unstyled_text_view_uses_base_tokens_for_link_and_input_selection(cx: &mut TestAppContext) {
1472        cx.update(crate::init);
1473        cx.update(|cx| {
1474            let colors = &mut crate::Theme::global_mut(cx).tokens.colors;
1475            colors.primary = gpui::rgb_to_hsla(gpui::rgb(0x55aaff));
1476            colors.selection = gpui::rgb_to_hsla(gpui::rgb(0x335577));
1477        });
1478        let (root, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new("[link](url)", cx));
1479        let cx: &mut VisualTestContext = cx;
1480
1481        cx.run_until_parked();
1482        root.read_with(cx, |root, cx| {
1483            let style = &root.text_view.read(cx).text_view_style;
1484            assert_eq!(style.link(), gpui::rgb_to_hsla(gpui::rgb(0x55aaff)));
1485            assert_eq!(style.selection(), gpui::rgb_to_hsla(gpui::rgb(0x335577)));
1486        });
1487    }
1488
1489    impl TextViewTestRoot {
1490        fn new(text: &str, cx: &mut Context<Self>) -> Self {
1491            let text = text.to_string();
1492            let text_view = cx.new(|cx| TextViewState::markdown(&text, cx));
1493            Self { text_view }
1494        }
1495    }
1496
1497    impl Render for TextViewTestRoot {
1498        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1499            div()
1500                .w(px(160.))
1501                .child(
1502                    div()
1503                        .h(px(24.))
1504                        .overflow_hidden()
1505                        .child(TextView::new(&self.text_view).selectable(true)),
1506                )
1507                .child(div().h(px(40.)).child("footer"))
1508        }
1509    }
1510
1511    struct TableSelectionTestRoot {
1512        text_view: Entity<TextViewState>,
1513    }
1514
1515    impl Render for TableSelectionTestRoot {
1516        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1517            div()
1518                .debug_selector(|| "table-selection-root".into())
1519                .w(px(520.))
1520                .child(crate::TextSelectionLayer)
1521                .child(TextView::new(&self.text_view))
1522        }
1523    }
1524
1525    #[gpui::test]
1526    fn table_drag_selection_settles_without_requesting_idle_frames(cx: &mut TestAppContext) {
1527        cx.update(crate::init);
1528        let (_, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
1529            text_view: cx.new(|cx| {
1530                TextViewState::markdown(
1531                    "| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
1532                    cx,
1533                )
1534            }),
1535        });
1536        let cx: &mut VisualTestContext = cx;
1537
1538        cx.run_until_parked();
1539        let bounds = cx
1540            .debug_bounds("table-selection-root")
1541            .expect("table bounds");
1542        let start = point(bounds.left() + px(24.), bounds.top() + px(16.));
1543        let end = point(bounds.right() - px(24.), bounds.bottom() - px(16.));
1544        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1545        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1546        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1547
1548        assert!(cx.update(|window, cx| crate::TextSelection::has_selection(window, cx)));
1549        assert_eq!(
1550            cx.update(|window, cx| window.simulate_next_frame(cx)),
1551            0,
1552            "finished table selection must not continuously request frames"
1553        );
1554    }
1555
1556    struct InlineImageTextViewTestRoot {
1557        text_view: Entity<TextViewState>,
1558    }
1559
1560    impl InlineImageTextViewTestRoot {
1561        fn new(cx: &mut Context<Self>) -> Self {
1562            let text_view = cx.new(|cx| {
1563                TextViewState::markdown(
1564                    "Build Status ![inline image](https://example.com/image.svg) after",
1565                    cx,
1566                )
1567            });
1568            Self { text_view }
1569        }
1570    }
1571
1572    impl Render for InlineImageTextViewTestRoot {
1573        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1574            div()
1575                .w(px(420.))
1576                .child(TextView::new(&self.text_view).selectable(true))
1577        }
1578    }
1579
1580    #[gpui::test]
1581    fn inline_image_keeps_surrounding_text_on_same_line(cx: &mut TestAppContext) {
1582        cx.update(crate::init);
1583        let (content, cx) = cx.add_window_view(|_, cx| InlineImageTextViewTestRoot::new(cx));
1584        let cx: &mut VisualTestContext = cx;
1585
1586        cx.run_until_parked();
1587        cx.update(|window, cx| {
1588            let _ = window.draw(cx);
1589        });
1590
1591        let inline_bounds = content.read_with(cx, |content, cx| {
1592            content.text_view.read(cx).selection_adapter.text_bounds()
1593        });
1594
1595        assert_eq!(inline_bounds.len(), 2);
1596        assert_eq!(
1597            inline_bounds[0].top(),
1598            inline_bounds[1].top(),
1599            "text before and after an inline image should share a rendered line"
1600        );
1601        assert!(
1602            inline_bounds[1].left() - inline_bounds[0].right() > px(8.),
1603            "inline image should reserve horizontal space in the text layout"
1604        );
1605        assert!(
1606            inline_bounds[1].left() - inline_bounds[0].right() < px(40.),
1607            "unloaded inline image fallback should stay generic and compact"
1608        );
1609    }
1610
1611    #[gpui::test]
1612    fn inline_html_image_after_newline_does_not_panic(cx: &mut TestAppContext) {
1613        cx.update(crate::init);
1614        let (_, cx) = cx.add_window_view(|_, cx| {
1615            TextViewTestRoot::new(
1616                "Hi\n[<img src=\"https://example.com/image.svg\">](https://google.com/)",
1617                cx,
1618            )
1619        });
1620        let cx: &mut VisualTestContext = cx;
1621
1622        cx.run_until_parked();
1623        cx.update(|window, cx| {
1624            let _ = window.draw(cx);
1625        });
1626    }
1627
1628    #[gpui::test]
1629    fn list_item_renders_fenced_code_block_at_document_width(cx: &mut TestAppContext) {
1630        struct ListItemBlockRoot;
1631
1632        impl Render for ListItemBlockRoot {
1633            fn render(
1634                &mut self,
1635                _window: &mut Window,
1636                _cx: &mut Context<Self>,
1637            ) -> impl IntoElement {
1638                div().w(px(840.)).h(px(400.)).child(
1639                    crate::h_resizable("markdown-width-test")
1640                        .child(crate::resizable_panel().child(div()))
1641                        .child(crate::resizable_panel().child(
1642                            TextView::markdown(
1643                                "list-with-code",
1644                                "1. List item\n   ```rust\n   nested code\n   ```\n\n```rust\ntop-level code\n```",
1645                            )
1646                            .code_block_actions(|code_block, _, _| {
1647                                let selector = if code_block.code().contains("nested") {
1648                                    "nested-code-action"
1649                                } else {
1650                                    "top-level-code-action"
1651                                };
1652                                div()
1653                                    .debug_selector(move || selector.into())
1654                                    .child("Copy")
1655                            })
1656                            .scrollable(true)
1657                            .p_5()
1658                            .flex_none(),
1659                        )),
1660                )
1661            }
1662        }
1663
1664        cx.update(crate::init);
1665        let (_, cx) = cx.add_window_view(|_, _| ListItemBlockRoot);
1666        let cx: &mut VisualTestContext = cx;
1667
1668        cx.run_until_parked();
1669        cx.update(|window, cx| {
1670            let _ = window.draw(cx);
1671        });
1672
1673        let nested_action = cx.debug_bounds("nested-code-action").unwrap();
1674        let top_level_action = cx.debug_bounds("top-level-code-action").unwrap();
1675        assert!(
1676            top_level_action.right() - nested_action.right() < px(32.),
1677            "nested code block should fill the list item's available width"
1678        );
1679    }
1680
1681    /// Draw a Markdown table with a `table_actions` hook installed, and return
1682    /// the painted bounds of the actions element plus the data it received.
1683    /// `scroll` opts into the horizontally scrollable table layout.
1684    fn draw_table_with_actions(
1685        cx: &mut TestAppContext,
1686        scroll: bool,
1687    ) -> (Bounds<Pixels>, TableData) {
1688        use std::sync::{Arc, Mutex};
1689
1690        struct TableRoot {
1691            scroll: bool,
1692            captured: Arc<Mutex<Vec<TableData>>>,
1693        }
1694
1695        impl Render for TableRoot {
1696            fn render(
1697                &mut self,
1698                _window: &mut Window,
1699                _cx: &mut Context<Self>,
1700            ) -> impl IntoElement {
1701                let captured = self.captured.clone();
1702                let mut table_style = StyleRefinement::default();
1703                if self.scroll {
1704                    table_style.overflow.x = Some(Overflow::Scroll);
1705                }
1706
1707                div().w(px(320.)).child(
1708                    TextView::markdown(
1709                        "table-actions",
1710                        "| Name | Age |\n|:--|--:|\n| Alice | 30 |\n| Bob | 41 |",
1711                    )
1712                    .style(TextViewStyle::default().with_table(table_style))
1713                    .table_actions(move |table, _, _| {
1714                        if let Ok(mut captured) = captured.lock() {
1715                            captured.push(table.clone());
1716                        }
1717                        div().debug_selector(|| "table-action".into()).child("Copy")
1718                    }),
1719                )
1720            }
1721        }
1722
1723        cx.update(crate::init);
1724        let captured = Arc::new(Mutex::new(Vec::new()));
1725        let (_, cx) = cx.add_window_view({
1726            let captured = captured.clone();
1727            move |_, _| TableRoot { scroll, captured }
1728        });
1729        let cx: &mut VisualTestContext = cx;
1730
1731        cx.run_until_parked();
1732        cx.update(|window, cx| {
1733            let _ = window.draw(cx);
1734        });
1735
1736        let bounds = cx
1737            .debug_bounds("table-action")
1738            .expect("table actions should be painted");
1739        let data = captured
1740            .lock()
1741            .expect("captured table data")
1742            .last()
1743            .cloned()
1744            .expect("table actions hook should receive the table");
1745
1746        (bounds, data)
1747    }
1748
1749    #[gpui::test]
1750    fn table_actions_render_below_the_table(cx: &mut TestAppContext) {
1751        for scroll in [false, true] {
1752            let (bounds, data) = draw_table_with_actions(cx, scroll);
1753
1754            // Header plus two data rows are painted above the actions row.
1755            assert!(
1756                bounds.top() > px(40.),
1757                "actions should sit below the table (scroll: {scroll}), got {:?}",
1758                bounds.top()
1759            );
1760            assert_eq!(data.headers, vec!["Name", "Age"]);
1761            assert_eq!(data.rows, vec![vec!["Alice", "30"], vec!["Bob", "41"]]);
1762            assert_eq!(
1763                data.markdown,
1764                "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n| Bob | 41 |"
1765            );
1766            assert_eq!(data.span, Some(0..52));
1767        }
1768    }
1769
1770    #[test]
1771    fn plugin_accepts_text_view_plugins_beyond_markdown() {
1772        let view = TextView::markdown("plugin-test", "").plugin(DummyTextViewPlugin);
1773
1774        assert!(view.selectable);
1775    }
1776
1777    #[test]
1778    fn syntax_highlighting_is_opt_in() {
1779        let default_view = TextView::markdown("default-code", "```rust\nfn main() {}\n```");
1780        assert!(default_view.code_block_highlighter.is_none());
1781
1782        let view = default_view.code_block_highlighter(|block| {
1783            vec![(
1784                0..block.code().len(),
1785                gpui::HighlightStyle {
1786                    color: Some(gpui::rgb_to_hsla(gpui::rgb(0x3366ff))),
1787                    ..Default::default()
1788                },
1789            )]
1790        });
1791        assert!(view.code_block_highlighter.is_some());
1792    }
1793
1794    #[gpui::test]
1795    fn clipped_markdown_link_does_not_open(cx: &mut TestAppContext) {
1796        cx.update(crate::init);
1797        let (_, cx) = cx.add_window_view(|_, cx| {
1798            TextViewTestRoot::new("visible\n\n[hidden](https://example.com)", cx)
1799        });
1800        let cx: &mut VisualTestContext = cx;
1801
1802        cx.simulate_click(point(px(10.), px(34.)), Modifiers::default());
1803
1804        assert_eq!(cx.opened_url(), None);
1805    }
1806
1807    struct MaxLinesTestRoot {
1808        text_view: Entity<TextViewState>,
1809        max_lines: usize,
1810    }
1811
1812    impl MaxLinesTestRoot {
1813        fn new(text: &str, max_lines: usize, cx: &mut Context<Self>) -> Self {
1814            let text_view = cx.new(|cx| TextViewState::markdown(text, cx));
1815            Self {
1816                text_view,
1817                max_lines,
1818            }
1819        }
1820    }
1821
1822    impl Render for MaxLinesTestRoot {
1823        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1824            div()
1825                .w(px(200.))
1826                .child(TextView::new(&self.text_view).max_lines(self.max_lines))
1827        }
1828    }
1829
1830    #[test]
1831    fn the_clip_only_moves_for_a_straddling_glyph_line() {
1832        use super::line_safe_clip_bottom;
1833        use crate::text::state::LineSpan;
1834
1835        let spans = [
1836            // Lines end at 20 / 40 / 60.
1837            LineSpan {
1838                top: px(0.),
1839                bottom: px(60.),
1840                line_height: px(20.),
1841            },
1842            // A second block after an 8px gap; lines end at 88 / 108 / 128.
1843            LineSpan {
1844                top: px(68.),
1845                bottom: px(128.),
1846                line_height: px(20.),
1847            },
1848        ];
1849
1850        // Content continues well past the box in every case but the last.
1851        let below = px(400.);
1852
1853        // A box ending inside the line 88..108 leaves that line out whole.
1854        assert_eq!(
1855            line_safe_clip_bottom(&spans, px(100.), below),
1856            Some(px(88.))
1857        );
1858
1859        // A box ending on a line boundary has nothing to pull the clip up for.
1860        assert_eq!(line_safe_clip_bottom(&spans, px(88.), below), None);
1861
1862        // A strip below the last line shorter than a line — the border and
1863        // padding a block leads with — is not worth showing.
1864        assert_eq!(line_safe_clip_bottom(&spans, px(64.), below), Some(px(60.)));
1865
1866        // One taller than a line is: whatever crosses the edge keeps the part
1867        // that fits rather than leaving the box half empty.
1868        let one_block = [LineSpan {
1869            top: px(0.),
1870            bottom: px(60.),
1871            line_height: px(20.),
1872        }];
1873        assert_eq!(line_safe_clip_bottom(&one_block, px(200.), below), None);
1874
1875        // Nothing crosses the edge at all: the space under the last line is
1876        // the box's own, not a scrap of something below.
1877        assert_eq!(line_safe_clip_bottom(&spans, px(130.), px(128.)), None);
1878    }
1879
1880    #[test]
1881    fn a_line_taller_than_the_budget_keeps_the_part_that_fits() {
1882        use super::line_safe_clip_bottom;
1883        use crate::text::state::LineSpan;
1884
1885        // A heading line of 28px, in a box capped at one 26px body line.
1886        let heading = [LineSpan {
1887            top: px(70.),
1888            bottom: px(98.),
1889            line_height: px(28.),
1890        }];
1891
1892        assert_eq!(line_safe_clip_bottom(&heading, px(96.), px(400.)), None);
1893    }
1894
1895    #[test]
1896    fn the_clip_does_not_stop_on_a_row_of_border_and_padding() {
1897        use super::line_safe_clip_bottom;
1898        use crate::text::state::LineSpan;
1899
1900        // Two table rows, each one line of text, 9px of border and padding
1901        // between them.
1902        let rows = [
1903            LineSpan {
1904                top: px(100.),
1905                bottom: px(126.),
1906                line_height: px(26.),
1907            },
1908            LineSpan {
1909                top: px(135.),
1910                bottom: px(161.),
1911                line_height: px(26.),
1912            },
1913        ];
1914
1915        // Leaving out the second row's text would strand the 9px it leads
1916        // with, so the clip goes back to the row above it.
1917        assert_eq!(
1918            line_safe_clip_bottom(&rows, px(148.), px(400.)),
1919            Some(px(126.))
1920        );
1921    }
1922
1923    /// A clamped view nested the way an application nests one: inside a card,
1924    /// inside a region that fills a window of a known height. The height an
1925    /// ancestor hands down must not reach the clamped content and hide the
1926    /// overflow the clamp measures — with the content stretched to the capped
1927    /// box, nothing looks clipped and lines get cut in half.
1928    struct ClampedPageRoot {
1929        text_view: Entity<TextViewState>,
1930        max_lines: usize,
1931    }
1932
1933    impl Render for ClampedPageRoot {
1934        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1935            use crate::{h_flex, v_flex};
1936
1937            v_flex()
1938                .size_full()
1939                .p_4()
1940                .gap_4()
1941                .child(h_flex().max_w(px(480.)).gap_3().child("header"))
1942                .child(
1943                    v_flex()
1944                        .flex_1()
1945                        .min_h_0()
1946                        .gap_4()
1947                        .id("clamped-page-scroll")
1948                        .child(
1949                            v_flex()
1950                                .max_w(px(480.))
1951                                .p_3()
1952                                .gap_2()
1953                                .child(TextView::new(&self.text_view).max_lines(self.max_lines)),
1954                        )
1955                        .overflow_y_scroll(),
1956                )
1957        }
1958    }
1959
1960    #[gpui::test]
1961    fn max_lines_measures_overflow_inside_a_sized_page(cx: &mut TestAppContext) {
1962        cx.update(crate::init);
1963        let (root, cx) = cx.add_window_view(|_, cx| {
1964            let text_view = cx.new(|cx| {
1965                TextViewState::markdown(
1966                    "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth\n\nseventh",
1967                    cx,
1968                )
1969            });
1970            ClampedPageRoot {
1971                text_view,
1972                max_lines: 3,
1973            }
1974        });
1975        let cx: &mut VisualTestContext = cx;
1976
1977        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
1978    }
1979
1980    #[gpui::test]
1981    fn max_lines_clamps_overflowing_content(cx: &mut TestAppContext) {
1982        cx.update(crate::init);
1983        let (root, cx) = cx.add_window_view(|_, cx| {
1984            MaxLinesTestRoot::new(
1985                "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth",
1986                2,
1987                cx,
1988            )
1989        });
1990        let cx: &mut VisualTestContext = cx;
1991
1992        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
1993    }
1994
1995    #[gpui::test]
1996    fn max_lines_leaves_short_content_unclamped(cx: &mut TestAppContext) {
1997        cx.update(crate::init);
1998        let (root, cx) = cx.add_window_view(|_, cx| MaxLinesTestRoot::new("only line", 3, cx));
1999        let cx: &mut VisualTestContext = cx;
2000
2001        assert!(!root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
2002    }
2003
2004    #[gpui::test]
2005    fn heading_refinement_changes_rendered_heading_geometry(cx: &mut TestAppContext) {
2006        struct HeadingStyleRoot;
2007
2008        impl Render for HeadingStyleRoot {
2009            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2010                div()
2011                    .flex()
2012                    .items_start()
2013                    .child(
2014                        div()
2015                            .debug_selector(|| "default-h1".into())
2016                            .child(TextView::markdown("default-h1-view", "# Heading")),
2017                    )
2018                    .child(div().debug_selector(|| "custom-h1".into()).child(
2019                        TextView::markdown("custom-heading-view", "# Heading").style(
2020                            TextViewStyle::default().with_heading(|level| {
2021                                if level == 1 {
2022                                    StyleRefinement::default().pb(rems(2.))
2023                                } else {
2024                                    StyleRefinement::default()
2025                                }
2026                            }),
2027                        ),
2028                    ))
2029                    .child(
2030                        div()
2031                            .debug_selector(|| "default-h2".into())
2032                            .child(TextView::markdown("default-h2-view", "## Heading")),
2033                    )
2034                    .child(div().debug_selector(|| "custom-h2".into()).child(
2035                        TextView::markdown("custom-h2-view", "## Heading").style(
2036                            TextViewStyle::default().with_heading(|level| {
2037                                if level == 1 {
2038                                    StyleRefinement::default().pb(rems(2.))
2039                                } else {
2040                                    StyleRefinement::default()
2041                                }
2042                            }),
2043                        ),
2044                    ))
2045            }
2046        }
2047
2048        cx.update(crate::init);
2049        let (_, cx) = cx.add_window_view(|_, _| HeadingStyleRoot);
2050        cx.update(|window, cx| window.draw(cx).clear(cx));
2051
2052        let default_h1 = cx.debug_bounds("default-h1").unwrap();
2053        let custom_h1 = cx.debug_bounds("custom-h1").unwrap();
2054        let default_h2 = cx.debug_bounds("default-h2").unwrap();
2055        let custom_h2 = cx.debug_bounds("custom-h2").unwrap();
2056        assert!(custom_h1.size.height > default_h1.size.height);
2057        assert_eq!(custom_h2.size.height, default_h2.size.height);
2058    }
2059
2060    #[gpui::test]
2061    fn markdown_link_opens_url_without_handler(cx: &mut TestAppContext) {
2062        cx.update(crate::init);
2063        let (_, cx) =
2064            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
2065        let cx: &mut VisualTestContext = cx;
2066
2067        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
2068
2069        assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
2070    }
2071
2072    #[gpui::test]
2073    fn right_click_does_not_open_url_without_handler(cx: &mut TestAppContext) {
2074        cx.update(crate::init);
2075        let (_, cx) =
2076            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
2077        let cx: &mut VisualTestContext = cx;
2078
2079        cx.simulate_mouse_down(
2080            point(px(10.), px(10.)),
2081            MouseButton::Right,
2082            Modifiers::default(),
2083        );
2084        cx.simulate_mouse_up(
2085            point(px(10.), px(10.)),
2086            MouseButton::Right,
2087            Modifiers::default(),
2088        );
2089
2090        assert_eq!(cx.opened_url(), None);
2091    }
2092
2093    #[gpui::test]
2094    fn link_handler_receives_button_and_modifiers(cx: &mut TestAppContext) {
2095        use std::sync::{Arc, Mutex};
2096
2097        struct LinkRoot {
2098            text_view: Entity<TextViewState>,
2099            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
2100        }
2101
2102        impl Render for LinkRoot {
2103            fn render(
2104                &mut self,
2105                _window: &mut Window,
2106                _cx: &mut Context<Self>,
2107            ) -> impl IntoElement {
2108                let clicks = self.clicks.clone();
2109                div()
2110                    .w(px(240.))
2111                    .child(
2112                        TextView::new(&self.text_view).on_link_click(move |url, event, _, _| {
2113                            clicks.lock().unwrap().push((url.clone(), event.clone()));
2114                        }),
2115                    )
2116            }
2117        }
2118
2119        cx.update(crate::init);
2120        let clicks = Arc::new(Mutex::new(Vec::new()));
2121        let captured = clicks.clone();
2122        let (_, cx) = cx.add_window_view(move |_, cx| LinkRoot {
2123            text_view: cx.new(|cx| TextViewState::markdown("[example](https://example.com)", cx)),
2124            clicks,
2125        });
2126        let cx: &mut VisualTestContext = cx;
2127
2128        let mut modifiers = Modifiers::default();
2129        modifiers.control = true;
2130        cx.simulate_click(point(px(10.), px(10.)), modifiers);
2131        cx.simulate_mouse_down(
2132            point(px(10.), px(10.)),
2133            MouseButton::Middle,
2134            Modifiers::default(),
2135        );
2136        cx.simulate_mouse_up(
2137            point(px(10.), px(10.)),
2138            MouseButton::Middle,
2139            Modifiers::default(),
2140        );
2141        cx.simulate_mouse_down(
2142            point(px(10.), px(10.)),
2143            MouseButton::Right,
2144            Modifiers::default(),
2145        );
2146        cx.simulate_mouse_up(
2147            point(px(10.), px(10.)),
2148            MouseButton::Right,
2149            Modifiers::default(),
2150        );
2151
2152        let clicks = captured.lock().unwrap();
2153        assert_eq!(clicks.len(), 3);
2154        assert_eq!(clicks[0].0, "https://example.com");
2155        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
2156        assert!(clicks[0].1.modifiers().control);
2157        assert!(clicks[1].1.is_middle_click());
2158        assert!(clicks[2].1.is_right_click());
2159        assert_eq!(cx.opened_url(), None);
2160    }
2161
2162    #[gpui::test]
2163    fn inline_object_inherits_bold_and_link_clicks_without_opening_on_drag(
2164        cx: &mut TestAppContext,
2165    ) {
2166        use std::sync::{Arc, Mutex};
2167        struct Root {
2168            state: Entity<TextViewState>,
2169            clicks: Arc<Mutex<Vec<SharedString>>>,
2170        }
2171        impl Render for Root {
2172            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2173                let clicks = self.clicks.clone();
2174                let extensions = crate::text::MarkdownExtensions::default().plugin(
2175                    crate::text::markdown_ext::TestInlinePlugin::new("math")
2176                        .parse_with(|node, _| {
2177                            matches!(node, markdown::mdast::Node::InlineMath(_)).then(|| {
2178                                super::super::MarkdownNode::new("math", ()).text("formula")
2179                            })
2180                        })
2181                        .render_with(|_, context, _, _| {
2182                            assert_eq!(context.text_style().font_weight, gpui::FontWeight::BOLD);
2183                            Some(super::super::InlineElement::new(div().child("formula")))
2184                        }),
2185                );
2186                div().w(px(300.)).child(crate::TextSelectionLayer).child(
2187                    TextView::new(&self.state)
2188                        .markdown_extensions(extensions)
2189                        .on_link_click(move |url, _, _, _| {
2190                            clicks.lock().unwrap().push(url.clone())
2191                        }),
2192                )
2193            }
2194        }
2195        cx.update(crate::init);
2196        let clicks = Arc::new(Mutex::new(Vec::new()));
2197        let captured = clicks.clone();
2198        let (root, cx) = cx.add_window_view(move |_, cx| Root {
2199            state: cx.new(|cx| TextViewState::markdown("**[$x$](https://example.com)**", cx)),
2200            clicks,
2201        });
2202        let cx: &mut VisualTestContext = cx;
2203        cx.run_until_parked();
2204        cx.update(|window, cx| {
2205            let _ = window.draw(cx);
2206        });
2207        let bounds = root.read_with(cx, |root, cx| {
2208            root.state.read(cx).selection_adapter.text_bounds()[0]
2209        });
2210        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
2211            cx.simulate_mouse_down(bounds.center(), button, Modifiers::default());
2212            cx.simulate_mouse_up(bounds.center(), button, Modifiers::default());
2213        }
2214        assert_eq!(captured.lock().unwrap().len(), 3);
2215        let start = point(bounds.left() + px(1.), bounds.center().y);
2216        let end = point(bounds.right() - px(1.), bounds.center().y);
2217        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2218        cx.update(|window, cx| {
2219            let _ = window.draw(cx);
2220        });
2221        cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
2222        cx.update(|window, cx| {
2223            let _ = window.draw(cx);
2224        });
2225        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2226        assert_eq!(captured.lock().unwrap().len(), 3);
2227    }
2228
2229    #[gpui::test]
2230    fn linked_image_handler_receives_left_middle_and_right_clicks(cx: &mut TestAppContext) {
2231        use std::sync::{Arc, Mutex};
2232
2233        struct LinkedImageRoot {
2234            text_view: Entity<TextViewState>,
2235            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
2236        }
2237
2238        impl Render for LinkedImageRoot {
2239            fn render(
2240                &mut self,
2241                _window: &mut Window,
2242                _cx: &mut Context<Self>,
2243            ) -> impl IntoElement {
2244                let clicks = self.clicks.clone();
2245                div().w(px(160.)).child(
2246                    TextView::new(&self.text_view)
2247                        .selectable(true)
2248                        .on_link_click(move |url, event, _, _| {
2249                            clicks.lock().unwrap().push((url.clone(), event.clone()));
2250                        }),
2251                )
2252            }
2253        }
2254
2255        cx.update(crate::init);
2256        let clicks = Arc::new(Mutex::new(Vec::new()));
2257        let captured = clicks.clone();
2258        let (content, cx) = cx.add_window_view(move |_, cx| LinkedImageRoot {
2259                text_view: cx.new(|cx| {
2260                    TextViewState::markdown(
2261                        r#"Before [<img src="https://example.com/image.svg" width="32" height="32">](https://example.com/image-link) after."#,
2262                        cx,
2263                    )
2264                }),
2265                clicks,
2266            }
2267        );
2268        let cx: &mut VisualTestContext = cx;
2269        cx.run_until_parked();
2270        cx.update(|window, cx| {
2271            let _ = window.draw(cx);
2272        });
2273
2274        let inline_bounds = content.read_with(cx, |content, cx| {
2275            content.text_view.read(cx).selection_adapter.text_bounds()
2276        });
2277        assert!(
2278            inline_bounds.len() >= 2,
2279            "linked image needs text bounds on both sides: {inline_bounds:?}"
2280        );
2281        assert!(
2282            inline_bounds[1].left() - inline_bounds[0].right() >= px(24.),
2283            "linked image did not reserve the expected click target: {inline_bounds:?}"
2284        );
2285        let position = point(
2286            inline_bounds[0].right() + (inline_bounds[1].left() - inline_bounds[0].right()) * 0.5,
2287            inline_bounds[0].top() + px(8.),
2288        );
2289        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
2290            cx.simulate_mouse_down(position, button, Modifiers::default());
2291            cx.simulate_mouse_up(position, button, Modifiers::default());
2292        }
2293
2294        let clicks = captured.lock().unwrap();
2295        assert_eq!(clicks.len(), 3);
2296        assert!(
2297            clicks
2298                .iter()
2299                .all(|(url, _)| url == "https://example.com/image-link")
2300        );
2301        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
2302        assert!(clicks[1].1.is_middle_click());
2303        assert!(clicks[2].1.is_right_click());
2304        assert_eq!(cx.opened_url(), None);
2305    }
2306
2307    #[gpui::test]
2308    fn clipped_markdown_cannot_start_selection(cx: &mut TestAppContext) {
2309        cx.update(crate::init);
2310        let (view, cx) = cx
2311            .add_window_view(|_, cx| TextViewTestRoot::new("visible\n\nhidden selection text", cx));
2312        let cx: &mut VisualTestContext = cx;
2313
2314        cx.simulate_mouse_down(
2315            point(px(10.), px(34.)),
2316            MouseButton::Left,
2317            Modifiers::default(),
2318        );
2319        cx.simulate_mouse_move(
2320            point(px(90.), px(34.)),
2321            Some(MouseButton::Left),
2322            Modifiers::default(),
2323        );
2324        cx.simulate_mouse_up(
2325            point(px(90.), px(34.)),
2326            MouseButton::Left,
2327            Modifiers::default(),
2328        );
2329
2330        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2331        assert!(
2332            selected_text.is_empty(),
2333            "unexpected selection: {selected_text:?}"
2334        );
2335    }
2336
2337    /// A tall selectable TextView clipped by a short `overflow_hidden` viewport,
2338    /// with a large blank footer below so a drag can extend the selection band
2339    /// past the bottom of the clip while still proxy-anchoring to the view.
2340    struct ClippedTallTextViewTestRoot {
2341        text_view: Entity<TextViewState>,
2342    }
2343
2344    impl ClippedTallTextViewTestRoot {
2345        fn new(cx: &mut Context<Self>) -> Self {
2346            // Four separate blocks; only the first (and maybe part of the
2347            // second) fit inside the 40px clip. "charlie"/"delta" render well
2348            // below it.
2349            let text_view =
2350                cx.new(|cx| TextViewState::markdown("alpha\n\nbravo\n\ncharlie\n\ndelta", cx));
2351            Self { text_view }
2352        }
2353    }
2354
2355    impl Render for ClippedTallTextViewTestRoot {
2356        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2357            div()
2358                .w(px(200.))
2359                .child(crate::TextSelectionLayer)
2360                .child(
2361                    div()
2362                        .h(px(40.))
2363                        .overflow_hidden()
2364                        .child(TextView::new(&self.text_view).selectable(true)),
2365                )
2366                // A tall blank footer so a drag can reach a y below the clipped
2367                // text; a press there proxy-anchors to the TextView above.
2368                .child(div().h(px(160.)))
2369        }
2370    }
2371
2372    /// Regression for copying a selection taller than the visible viewport.
2373    ///
2374    /// The selection band runs from visible text at the top down to a point
2375    /// far below the clip. Every glyph of the painted TextView is laid out even
2376    /// though the lower ones are clipped away, so the copied text must include
2377    /// the clipped-out "charlie"/"delta" — not just what is on screen. This
2378    /// guards against re-adding a `content_mask` gate in
2379    /// `Inline::layout_selections`.
2380    #[gpui::test]
2381    fn selection_band_beyond_clip_copies_offscreen_text(cx: &mut TestAppContext) {
2382        cx.update(crate::init);
2383        let (content, cx) = cx.add_window_view(|_, cx| ClippedTallTextViewTestRoot::new(cx));
2384        let cx: &mut VisualTestContext = cx;
2385
2386        cx.run_until_parked();
2387        cx.update(|window, cx| {
2388            let _ = window.draw(cx);
2389        });
2390
2391        // Anchor on visible text near the top, then drag to a point well below
2392        // the 40px clip (into the blank footer) and to the far right so the
2393        // last line is fully covered.
2394        cx.simulate_mouse_down(
2395            point(px(2.), px(8.)),
2396            MouseButton::Left,
2397            Modifiers::default(),
2398        );
2399        cx.update(|window, cx| {
2400            let _ = window.draw(cx);
2401        });
2402        cx.simulate_mouse_move(
2403            point(px(180.), px(150.)),
2404            Some(MouseButton::Left),
2405            Modifiers::default(),
2406        );
2407        cx.update(|window, cx| {
2408            let _ = window.draw(cx);
2409        });
2410        cx.simulate_mouse_up(
2411            point(px(180.), px(150.)),
2412            MouseButton::Left,
2413            Modifiers::default(),
2414        );
2415        cx.update(|window, cx| {
2416            let _ = window.draw(cx);
2417        });
2418
2419        let selected_text =
2420            content.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2421        assert!(
2422            selected_text.contains("delta"),
2423            "clipped-out text was not copied: {selected_text:?}"
2424        );
2425        assert!(
2426            selected_text.contains("charlie"),
2427            "clipped-out text was not copied: {selected_text:?}"
2428        );
2429    }
2430
2431    #[gpui::test]
2432    fn double_click_selects_word(cx: &mut TestAppContext) {
2433        cx.update(crate::init);
2434        let (view, cx) =
2435            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
2436
2437        let cx: &mut VisualTestContext = cx;
2438        cx.run_until_parked();
2439        cx.update(|window, cx| {
2440            let _ = window.draw(cx);
2441        });
2442        let position = point(px(10.), px(16.));
2443        cx.simulate_event(MouseDownEvent {
2444            position,
2445            modifiers: Modifiers::default(),
2446            button: MouseButton::Left,
2447            click_count: 2,
2448            first_mouse: false,
2449        });
2450        cx.simulate_event(MouseUpEvent {
2451            position,
2452            modifiers: Modifiers::default(),
2453            button: MouseButton::Left,
2454            click_count: 2,
2455        });
2456        cx.update(|window, cx| {
2457            let _ = window.draw(cx);
2458        });
2459
2460        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2461        assert_eq!(selected_text.trim(), "quick");
2462    }
2463
2464    #[gpui::test]
2465    fn triple_click_selects_paragraph(cx: &mut TestAppContext) {
2466        cx.update(crate::init);
2467        let (view, cx) =
2468            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
2469
2470        let cx: &mut VisualTestContext = cx;
2471        cx.run_until_parked();
2472        cx.update(|window, cx| {
2473            let _ = window.draw(cx);
2474        });
2475
2476        let position = point(px(10.), px(10.));
2477        cx.simulate_event(MouseDownEvent {
2478            position,
2479            modifiers: Modifiers::default(),
2480            button: MouseButton::Left,
2481            click_count: 3,
2482            first_mouse: false,
2483        });
2484        cx.simulate_event(MouseUpEvent {
2485            position,
2486            modifiers: Modifiers::default(),
2487            button: MouseButton::Left,
2488            click_count: 3,
2489        });
2490        cx.update(|window, cx| {
2491            let _ = window.draw(cx);
2492        });
2493
2494        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2495        assert_eq!(selected_text.trim(), "quick select value");
2496    }
2497
2498    // Regression: markdown `TextView` items inside an outer `gpui::list` with
2499    // `measure_all` must keep a stable total content height while scrolling.
2500    // Before synchronous full-replace parsing, off-screen markdown views were
2501    // first measured with empty content and the scrollbar thumb jittered as the
2502    // total height grew during scrolling.
2503    #[gpui::test]
2504    fn outer_list_content_total_stable_while_scrolling(cx: &mut TestAppContext) {
2505        use gpui::{ListAlignment, ListState, list};
2506
2507        const ITEMS: &[&str] = &[
2508            "# Heading\n\nA paragraph long enough to wrap across several lines and produce a non-trivial height.",
2509            "Short.",
2510            "Paragraph A\n\nParagraph B\n\nParagraph C with more words to increase the height.",
2511            "## Subheading\n\n- One\n- Two\n- Three\n\nClosing paragraph.",
2512            "Only one line.",
2513            "**Bold**: medium length text with `code` mixed with regular words.",
2514            "1. First\n2. Second\n3. Third\n\nA short closing paragraph.",
2515            "A long message with enough words to wrap across multiple lines, create a taller item, and verify that off-screen measurement matches visible measurement.",
2516        ];
2517        let n = 40usize;
2518
2519        struct ListRoot {
2520            state: ListState,
2521        }
2522        impl Render for ListRoot {
2523            fn render(&mut self, _w: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2524                div().w(px(360.)).h(px(500.)).child(
2525                    list(self.state.clone(), |ix, _w, _cx| {
2526                        div()
2527                            .w_full()
2528                            .child(TextView::markdown(
2529                                ("md", ix as u64),
2530                                ITEMS[ix % ITEMS.len()],
2531                            ))
2532                            .into_any_element()
2533                    })
2534                    .size_full(),
2535                )
2536            }
2537        }
2538
2539        cx.update(crate::init);
2540        let state = ListState::new(n, ListAlignment::Top, px(2048.)).measure_all();
2541        let probe = state.clone();
2542        let (_view, cx) = cx.add_window_view(|_w, _cx| ListRoot { state });
2543        let cx: &mut VisualTestContext = cx;
2544
2545        cx.run_until_parked();
2546        cx.update(|w, cx| {
2547            let _ = w.draw(cx);
2548        });
2549        cx.run_until_parked();
2550        cx.update(|w, cx| {
2551            let _ = w.draw(cx);
2552        });
2553
2554        let total = |p: &ListState| {
2555            f32::from(p.max_offset_for_scrollbar().y + p.viewport_bounds().size.height)
2556        };
2557        let mut totals = vec![total(&probe)];
2558        for _ in 0..20 {
2559            probe.scroll_by(px(150.));
2560            cx.update(|w, cx| {
2561                let _ = w.draw(cx);
2562            });
2563            cx.run_until_parked();
2564            totals.push(total(&probe));
2565        }
2566        let min = totals.iter().cloned().fold(f32::INFINITY, f32::min);
2567        let max = totals.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2568        println!(
2569            "OUTER_LIST_PROBE min={min:.1} max={max:.1} delta={:.1}",
2570            max - min
2571        );
2572        assert!(
2573            (max - min) < 2.0,
2574            "list content total jittered while scrolling: min={min} max={max} totals={totals:?}"
2575        );
2576    }
2577}