Skip to main content

wgpui_base/text/
text_view.rs

1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use wgpui::prelude::FluentBuilder as _;
4use wgpui::{
5    AnyElement, App, Bounds, ClickEvent, ContentMask, Element, ElementId, Entity, Global,
6    GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement, IntoElement,
7    LayoutId, MouseButton, ParentElement, Pixels, Refineable as _, SharedString, StyleRefinement,
8    Styled, Window, div, point, px,
9};
10
11use crate::StyledExt;
12use crate::text::TextViewFormat;
13use crate::text::markdown_ext::{MarkdownExtensions, MarkdownNode, MarkdownPlugin};
14use crate::text::node::{CodeBlock, TableData};
15use crate::text::range_highlight::{PendingReveal, RevealProgress};
16use crate::text::state::{LineSpan, SelectionFormat, TextViewState};
17use crate::text::stream_fade::TextViewMotion;
18use crate::{GlobalState, TextSelection, text::TextViewStyle};
19
20/// Type for code block actions generator function.
21pub(crate) type CodeBlockActionsFn =
22    dyn Fn(&CodeBlock, &mut Window, &mut App) -> AnyElement + Send + Sync;
23
24pub(crate) type CodeBlockHighlighterFn =
25    dyn Fn(&CodeBlock) -> Vec<(Range<usize>, wgpui::HighlightStyle)> + Send + Sync;
26
27/// Application-wide defaults for TextViews that do not provide explicit
28/// presentation or syntax-highlighting overrides.
29#[derive(Clone, Default)]
30pub struct TextViewDefaults {
31    style: Option<TextViewStyle>,
32    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
33    inherit_text_color: bool,
34}
35
36impl Global for TextViewDefaults {}
37
38impl TextViewDefaults {
39    /// Creates defaults that leave every text view as Base renders it.
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    /// Sets the style every text view starts from.
45    pub fn with_style(mut self, style: TextViewStyle) -> Self {
46        self.style = Some(style);
47        self
48    }
49
50    /// The style every text view starts from, when set.
51    pub(crate) fn style(&self) -> Option<&TextViewStyle> {
52        self.style.as_ref()
53    }
54
55    /// The syntax highlighter for fenced code blocks, when set.
56    pub(crate) fn code_block_highlighter(&self) -> Option<Arc<CodeBlockHighlighterFn>> {
57        self.code_block_highlighter.clone()
58    }
59
60    /// Sets the syntax highlighter used for fenced code blocks.
61    pub fn with_code_block_highlighter<F>(mut self, highlighter: F) -> Self
62    where
63        F: Fn(&CodeBlock) -> Vec<(Range<usize>, wgpui::HighlightStyle)> + Send + Sync + 'static,
64    {
65        self.code_block_highlighter = Some(Arc::new(highlighter));
66        self
67    }
68
69    /// Sets whether text views without an explicit [`TextView::style`] follow
70    /// the text color their container sets, default false.
71    ///
72    /// The body text takes that color. On a surface inverted from the page,
73    /// such as a `primary` fill, links, muted text, code, borders and
74    /// selection are derived from it too, and the installed syntax highlighter
75    /// is left out because its colors are made for the page. Enable this only
76    /// when every window sets a text color at its root, as Component's does.
77    pub fn with_inherit_text_color(mut self, inherit: bool) -> Self {
78        self.inherit_text_color = inherit;
79        self
80    }
81
82    /// Installs these defaults for the whole application.
83    pub fn install(self, cx: &mut App) {
84        cx.set_global(self);
85    }
86
87    /// Returns the installed defaults, or the Base ones when none were.
88    pub fn global(cx: &App) -> Self {
89        cx.try_global::<Self>().cloned().unwrap_or_default()
90    }
91
92    /// Whether a syntax highlighter was installed.
93    pub fn has_code_block_highlighter(&self) -> bool {
94        self.code_block_highlighter.is_some()
95    }
96
97    /// Whether text views follow the text color their container sets.
98    pub fn inherit_text_color(&self) -> bool {
99        self.inherit_text_color
100    }
101}
102
103/// Type for the table actions generator function.
104pub(crate) type TableActionsFn =
105    dyn Fn(&TableData, &mut Window, &mut App) -> AnyElement + Send + Sync;
106
107pub(crate) type ImageSourceFn = dyn Fn(&wgpui::SharedUri) -> wgpui::ImageSource + Send + Sync;
108
109pub(crate) type LinkClickHandlerFn =
110    dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
111
112/// Kept by the element only, so unlike the handlers the state carries, it
113/// may hold a `ScrollHandle`.
114pub(crate) type RevealHandlerFn = dyn Fn(Bounds<Pixels>, &mut Window, &mut App);
115
116pub(crate) fn handle_link_click(
117    handler: &Option<Arc<LinkClickHandlerFn>>,
118    url: SharedString,
119    event: ClickEvent,
120    window: &mut Window,
121    cx: &mut App,
122) {
123    if let Some(handler) = handler {
124        handler(&url, &event, window, cx);
125    } else if match &event {
126        ClickEvent::Mouse(click) => {
127            matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
128        }
129        ClickEvent::Keyboard(_) => true,
130        ClickEvent::Touch(click) => !click.long_press,
131    } {
132        cx.open_url(&url);
133    }
134}
135
136/// A text view that can render Markdown or HTML.
137///
138/// ## Goals
139///
140/// - Provide a rich text rendering component for such as Markdown or HTML,
141/// used to display rich text in GPUI application (e.g., Help messages, Release notes)
142/// - Support Markdown GFM and HTML (Simple HTML like Safari Reader Mode) for showing most common used markups.
143/// - Support Heading, Paragraph, Bold, Italic, StrikeThrough, Code, Link, Image, Blockquote, List, Table, HorizontalRule, CodeBlock ...
144///
145/// ## Not Goals
146///
147/// - Customization of the complex style (some simple styles will be supported)
148/// - Editing Markdown source; this view renders formatted content.
149/// - As a HTML viewer, we not support CSS, we only support basic HTML tags for used to as a content reader.
150///
151/// See also [`Self::markdown`] and [`Self::html`].
152#[derive(Clone)]
153pub struct TextView {
154    id: ElementId,
155    format: Option<TextViewFormat>,
156    text: Option<SharedString>,
157    pub(crate) state: Option<Entity<TextViewState>>,
158    text_view_style: Option<TextViewStyle>,
159    inline_code_style: Option<StyleRefinement>,
160    list_style: Option<StyleRefinement>,
161    blockquote_style: Option<StyleRefinement>,
162    style: StyleRefinement,
163    selectable: bool,
164    selection_format: SelectionFormat,
165    scrollable: bool,
166    max_lines: Option<usize>,
167    code_block_actions: Option<Arc<CodeBlockActionsFn>>,
168    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
169    table_actions: Option<Arc<TableActionsFn>>,
170    link_click_handler: Option<Arc<LinkClickHandlerFn>>,
171    image_source: Option<Arc<ImageSourceFn>>,
172    reveal_handler: Option<Rc<RevealHandlerFn>>,
173    markdown_extensions: Arc<MarkdownExtensions>,
174    motion: Option<TextViewMotion>,
175}
176
177/// A plugin that can configure a [`TextView`].
178pub trait TextViewPlugin {
179    fn setup(self, text_view: TextView) -> TextView;
180}
181
182impl<P> TextViewPlugin for P
183where
184    P: MarkdownPlugin,
185{
186    fn setup(self, mut text_view: TextView) -> TextView {
187        let extensions = Arc::make_mut(&mut text_view.markdown_extensions);
188        let current = std::mem::take(extensions);
189        *extensions = current.plugin(self);
190        text_view
191    }
192}
193
194impl Styled for TextView {
195    fn style(&mut self) -> &mut StyleRefinement {
196        &mut self.style
197    }
198}
199
200impl TextView {
201    /// Create new TextView with managed state.
202    pub fn new(state: &Entity<TextViewState>) -> Self {
203        Self {
204            id: ElementId::Name(state.entity_id().to_string().into()),
205            state: Some(state.clone()),
206            format: None,
207            text: None,
208            text_view_style: None,
209            inline_code_style: None,
210            list_style: None,
211            blockquote_style: None,
212            style: StyleRefinement::default(),
213            selectable: true,
214            selection_format: SelectionFormat::default(),
215            scrollable: false,
216            max_lines: None,
217            code_block_actions: None,
218            code_block_highlighter: None,
219            table_actions: None,
220            link_click_handler: None,
221            image_source: None,
222            reveal_handler: None,
223            markdown_extensions: Arc::default(),
224            motion: None,
225        }
226    }
227
228    /// Create a new markdown text view.
229    pub fn markdown(id: impl Into<ElementId>, markdown: impl Into<SharedString>) -> Self {
230        Self {
231            id: id.into(),
232            format: Some(TextViewFormat::Markdown),
233            text: Some(markdown.into()),
234            text_view_style: None,
235            inline_code_style: None,
236            list_style: None,
237            blockquote_style: None,
238            style: StyleRefinement::default(),
239            state: None,
240            selectable: true,
241            selection_format: SelectionFormat::default(),
242            scrollable: false,
243            max_lines: None,
244            code_block_actions: None,
245            code_block_highlighter: None,
246            table_actions: None,
247            link_click_handler: None,
248            image_source: None,
249            reveal_handler: None,
250            markdown_extensions: Arc::default(),
251            motion: None,
252        }
253    }
254
255    /// Create a new html text view.
256    pub fn html(id: impl Into<ElementId>, html: impl Into<SharedString>) -> Self {
257        Self {
258            id: id.into(),
259            format: Some(TextViewFormat::Html),
260            text: Some(html.into()),
261            text_view_style: None,
262            inline_code_style: None,
263            list_style: None,
264            blockquote_style: None,
265            style: StyleRefinement::default(),
266            state: None,
267            selectable: true,
268            selection_format: SelectionFormat::default(),
269            scrollable: false,
270            max_lines: None,
271            code_block_actions: None,
272            code_block_highlighter: None,
273            table_actions: None,
274            link_click_handler: None,
275            image_source: None,
276            reveal_handler: None,
277            markdown_extensions: Arc::default(),
278            motion: None,
279        }
280    }
281
282    /// Overrides the source of every document image, including embedded data URLs.
283    ///
284    /// Used for both rendering and intrinsic-size measurement. The returned source
285    /// is authoritative: pending or failed loads never fall back to the document URL.
286    /// Without this override, images use Base's default URI and data URL handling.
287    pub fn image_source<F>(mut self, resolver: F) -> Self
288    where
289        F: Fn(&wgpui::SharedUri) -> wgpui::ImageSource + Send + Sync + 'static,
290    {
291        self.image_source = Some(Arc::new(resolver));
292        self
293    }
294
295    /// Refines inline code typography, background, border, radius, and padding
296    /// over the resolved style. See [`TextViewStyle::with_inline_code_style`]
297    /// for the supported properties. Unspecified properties are inherited.
298    pub fn inline_code_style(mut self, style: StyleRefinement) -> Self {
299        self.inline_code_style = Some(super::style::normalize_inline_code_style(style));
300        self
301    }
302
303    /// Refines list markers over the resolved style. See
304    /// [`TextViewStyle::with_list_style`] for where it applies.
305    /// Unspecified properties are inherited.
306    pub fn list_style(mut self, style: StyleRefinement) -> Self {
307        self.list_style = Some(style);
308        self
309    }
310
311    /// Refines blockquotes over the resolved style. See
312    /// [`TextViewStyle::with_blockquote_style`] for where it applies.
313    /// Unspecified properties are inherited.
314    pub fn blockquote_style(mut self, style: StyleRefinement) -> Self {
315        self.blockquote_style = Some(style);
316        self
317    }
318
319    /// Set [`TextViewStyle`].
320    pub fn style(mut self, style: TextViewStyle) -> Self {
321        self.text_view_style = Some(style);
322        self
323    }
324
325    /// Set whether the text view is selectable, default is true.
326    pub fn selectable(mut self, selectable: bool) -> Self {
327        self.selectable = selectable;
328        self
329    }
330
331    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
332    ///
333    /// With [`SelectionFormat::Source`], selecting inside `**bold**` yields
334    /// `**bold**` (the Markdown source) rather than `bold`.
335    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
336        self.selection_format = selection_format;
337        self
338    }
339
340    /// Set the text view to be scrollable, default is false.
341    ///
342    /// ## If true for `scrollable`
343    ///
344    /// The `scrollable` mode used for large content,
345    /// will show scrollbar, but requires the parent to have a fixed height,
346    /// and use [`wgpui::list`] to render the content in a virtualized way.
347    ///
348    /// ## If false to fit content
349    ///
350    /// The TextView will expand to fit all content, no scrollbar.
351    /// This mode is suitable for small content, such as a few lines of text, a label, etc.
352    pub fn scrollable(mut self, scrollable: bool) -> Self {
353        self.scrollable = scrollable;
354        self
355    }
356
357    /// Clamp the rendered content to at most `n` lines of body text.
358    ///
359    /// The view's height is capped at `n` × the base line height, and a line
360    /// of glyphs is never cut in half: a line that would straddle the bottom
361    /// of the box is left out whole, across paragraphs, lists, headings, code
362    /// blocks and tables. Nothing is shown with less than a line of itself to
363    /// show, so the border and padding a table row leads with never strands at
364    /// the bottom; whatever has more than that is cut on the box edge and keeps
365    /// the part that fits, rather than disappearing and leaving blank space
366    /// behind.
367    ///
368    /// Check [`TextViewState::is_clamped`] (which answers for the frame that
369    /// was last painted) to decide whether to show an "expand" affordance.
370    ///
371    /// `n` counts lines of body text, so paragraph spacing and taller lines
372    /// mean fewer of them fit inside the capped height. A line taller than the
373    /// whole budget keeps the part that fits rather than emptying the box.
374    /// Ignored when [`Self::scrollable`] is set.
375    pub fn max_lines(mut self, max_lines: usize) -> Self {
376        self.max_lines = Some(max_lines);
377        self
378    }
379
380    /// Set custom block actions for code blocks.
381    ///
382    /// The closure receives the [`CodeBlock`],
383    /// and returns an element to display.
384    pub fn code_block_actions<F, E>(mut self, f: F) -> Self
385    where
386        F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
387        E: IntoElement,
388    {
389        self.code_block_actions = Some(Arc::new(move |code_block, window, cx| {
390            f(&code_block, window, cx).into_any_element()
391        }));
392        self
393    }
394
395    /// Adds opt-in syntax highlighting for fenced code blocks.
396    ///
397    /// Returned byte ranges are relative to [`CodeBlock::code`]. Invalid
398    /// ranges are discarded. Without this callback, code is unhighlighted.
399    pub fn code_block_highlighter<F>(mut self, highlighter: F) -> Self
400    where
401        F: Fn(&CodeBlock) -> Vec<(Range<usize>, wgpui::HighlightStyle)> + Send + Sync + 'static,
402    {
403        self.code_block_highlighter = Some(Arc::new(highlighter));
404        self
405    }
406
407    /// Like [`Self::code_block_highlighter`], with a highlighter that can be
408    /// handed to every frame.
409    ///
410    /// A code block reuses its highlights only while the highlighter is the
411    /// same `Arc`, so a view built every frame with a fresh closure
412    /// re-highlights every code block on every frame.
413    #[doc(hidden)]
414    pub fn shared_code_block_highlighter(
415        mut self,
416        highlighter: Arc<
417            dyn Fn(&CodeBlock) -> Vec<(Range<usize>, wgpui::HighlightStyle)> + Send + Sync,
418        >,
419    ) -> Self {
420        self.code_block_highlighter = Some(highlighter);
421        self
422    }
423
424    /// Set custom actions to be rendered below each Markdown table.
425    ///
426    /// The closure receives the [`TableData`],
427    /// and returns an element to display.
428    pub fn table_actions<F, E>(mut self, f: F) -> Self
429    where
430        F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
431        E: IntoElement,
432    {
433        self.table_actions = Some(Arc::new(move |table, window, cx| {
434            f(table, window, cx).into_any_element()
435        }));
436        self
437    }
438
439    /// Handle pointer events on rendered links.
440    ///
441    /// The handler receives the resolved URL and the original GPUI click event.
442    /// Without a handler, links open through App::open_url.
443    pub fn on_link_click<F>(mut self, handler: F) -> Self
444    where
445        F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
446    {
447        self.link_click_handler = Some(Arc::new(handler));
448        self
449    }
450
451    /// Scroll a container that does not follow scroll requests to the line
452    /// of [`TextViewState::reveal_range`].
453    ///
454    /// A `wgpui::list` scrolls to that line by itself; a `div` with
455    /// `overflow_y_scroll`, for one, does not. After a frame in which the
456    /// line was laid out but not visible, the handler receives its bounds in
457    /// window coordinates, to scroll the container, e.g. through its
458    /// `ScrollHandle`, until the line is visible.
459    pub fn on_reveal<F>(mut self, handler: F) -> Self
460    where
461        F: Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
462    {
463        self.reveal_handler = Some(Rc::new(handler));
464        self
465    }
466
467    /// Replace the Markdown extension registry.
468    pub fn markdown_extensions(mut self, extensions: MarkdownExtensions) -> Self {
469        self.markdown_extensions = Arc::new(extensions);
470        self
471    }
472
473    /// Set the motion policy; see [`TextViewMotion`]. Without one, the
474    /// state's own policy applies, which plays no motion by default.
475    pub fn motion(mut self, motion: TextViewMotion) -> Self {
476        self.motion = Some(motion);
477        self
478    }
479
480    /// Enable MDX JSX/expression parsing.
481    ///
482    /// This disables raw HTML parsing because `markdown-rs` gives HTML
483    /// priority over MDX when both are enabled.
484    pub fn markdown_mdx(mut self) -> Self {
485        let extensions = Arc::make_mut(&mut self.markdown_extensions);
486        *extensions = extensions.clone().mdx();
487        self
488    }
489
490    /// Register a custom block-level Markdown parser.
491    ///
492    /// The parser runs during Markdown AST conversion and must be independent
493    /// of [`Window`] / [`App`]. Store any parsed data in [`MarkdownNode`] and
494    /// render it later with [`Self::markdown_block_renderer`].
495    pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
496    where
497        F: for<'a> Fn(
498                &markdown::mdast::Node,
499                &crate::text::MarkdownParseContext<'a>,
500            ) -> Option<MarkdownNode>
501            + Send
502            + Sync
503            + 'static,
504    {
505        Arc::make_mut(&mut self.markdown_extensions).push_block_parser(parser);
506        self
507    }
508
509    /// Register a renderer for a custom block-level Markdown node name.
510    pub fn markdown_block_renderer<F, E>(
511        mut self,
512        name: impl Into<SharedString>,
513        renderer: F,
514    ) -> Self
515    where
516        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
517        E: IntoElement,
518    {
519        Arc::make_mut(&mut self.markdown_extensions).push_block_renderer(name, renderer);
520        self
521    }
522
523    /// Apply a reusable text view plugin.
524    pub fn plugin<P>(self, plugin: P) -> Self
525    where
526        P: TextViewPlugin,
527    {
528        plugin.setup(self)
529    }
530}
531
532impl IntoElement for TextView {
533    type Element = Self;
534
535    fn into_element(self) -> Self::Element {
536        self
537    }
538}
539
540pub struct TextViewLayoutState {
541    state: Entity<TextViewState>,
542    element: AnyElement,
543}
544
545pub struct TextViewPrepaintState {
546    hitbox: Hitbox,
547    /// Where paint has to pull the `max_lines` clip up to, because a glyph line
548    /// straddles the bottom of the box. `None` leaves the clip at the box edge,
549    /// where the container's hidden overflow already applies it.
550    clip_bottom: Option<Pixels>,
551    /// The touch handles this view owns, with their hitboxes.
552    touch_handles: crate::TouchHandleLayout,
553}
554
555/// Absorbs sub-pixel layout jitter: a line ending within a pixel of the box
556/// bottom counts as fitting inside it.
557const CLIP_EPSILON: Pixels = px(1.);
558
559/// The bottom of the last whole line at or above `y`, with the height of a line
560/// where it sits.
561fn last_line_bottom_above(spans: &[LineSpan], y: Pixels) -> Option<(Pixels, Pixels)> {
562    let mut last: Option<(Pixels, Pixels)> = None;
563    let mut keep = |bottom: Pixels, line_height: Pixels| {
564        if bottom <= y + CLIP_EPSILON && last.is_none_or(|(last, _)| bottom > last) {
565            last = Some((bottom, line_height));
566        }
567    };
568
569    for span in spans {
570        if span.line_height <= px(0.) {
571            continue;
572        }
573        let mut bottom = span.top + span.line_height;
574        while bottom <= span.bottom + CLIP_EPSILON {
575            keep(bottom, span.line_height);
576            bottom += span.line_height;
577        }
578        // The span's own bottom covers a last line taller than the rest.
579        keep(span.bottom, span.line_height);
580    }
581
582    last
583}
584
585/// Where to clip, given the lines a descendant `Inline` reported. `None` leaves
586/// the clip on the box edge.
587///
588/// Two things are never shown: half a line of glyphs, and anything with less
589/// than a line of itself to show. A line straddling `box_bottom` is left out
590/// whole, and so is the strip between it and the line before — the border and
591/// padding a table row leads with reads as a rendering fault rather than as a
592/// row. Whatever has more than a line to show is cut on the edge and keeps the
593/// part that fits, so the box holds no blank space it could have filled.
594fn line_safe_clip_bottom(
595    spans: &[LineSpan],
596    box_bottom: Pixels,
597    content_bottom: Pixels,
598) -> Option<Pixels> {
599    let mut clip = box_bottom;
600
601    for span in spans {
602        if span.line_height <= px(0.)
603            || span.top >= box_bottom
604            || span.bottom <= box_bottom + CLIP_EPSILON
605        {
606            continue;
607        }
608        let whole_lines = ((box_bottom - span.top) / span.line_height).floor();
609        let line_top = span.top + span.line_height * whole_lines;
610        // A line starting on the box edge is not straddling it.
611        if line_top < box_bottom - CLIP_EPSILON {
612            clip = clip.min(line_top);
613        }
614    }
615
616    let Some((last_line_bottom, line_height)) = last_line_bottom_above(spans, clip) else {
617        // Leaving the straddling line out would leave nothing at all — a first
618        // line taller than the whole budget, a heading in a one-line box. It
619        // keeps the part that fits instead, because an empty clamp reads as
620        // broken where a cut one reads as more to come.
621        return None;
622    };
623
624    // Snap away a scrap. Only content that continues past the box can leave
625    // one: the space under the last line of a document that fits is the box's
626    // own, not a piece of something below.
627    if content_bottom > box_bottom + CLIP_EPSILON {
628        let strip = clip - last_line_bottom;
629        if strip > CLIP_EPSILON && strip < line_height {
630            clip = last_line_bottom;
631        }
632    }
633
634    (clip < box_bottom - CLIP_EPSILON).then_some(clip)
635}
636
637impl Element for TextView {
638    type RequestLayoutState = TextViewLayoutState;
639    type PrepaintState = TextViewPrepaintState;
640
641    fn id(&self) -> Option<ElementId> {
642        Some(self.id.clone())
643    }
644
645    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
646        None
647    }
648
649    fn request_layout(
650        &mut self,
651        _: Option<&GlobalElementId>,
652        _: Option<&InspectorElementId>,
653        window: &mut Window,
654        cx: &mut App,
655    ) -> (LayoutId, Self::RequestLayoutState) {
656        let state = if let Some(state) = self.state.clone() {
657            state
658        } else {
659            let default_format = self.format.unwrap_or(TextViewFormat::Markdown);
660            let default_text = self.text.clone().unwrap_or_default();
661
662            let state = window.use_keyed_state(
663                SharedString::from(format!("{}/state", self.id)),
664                cx,
665                move |_, cx| {
666                    if default_format == TextViewFormat::Markdown {
667                        TextViewState::markdown(default_text.as_str(), cx)
668                    } else {
669                        TextViewState::html(default_text.as_str(), cx)
670                    }
671                },
672            );
673            self.state = Some(state.clone());
674            state
675        };
676
677        // `max_lines` needs the whole document laid out to snap the clip to a
678        // whole line, so it only applies to the fit-content mode.
679        let max_lines = self.max_lines.filter(|_| !self.scrollable);
680
681        // Resolve the style by reference: this runs every frame, and the
682        // style only reaches the state when it changed.
683        let defaults = cx.try_global::<TextViewDefaults>();
684        let theme_style;
685        let mut text_view_style = match (
686            &self.text_view_style,
687            defaults.and_then(|d| d.style.as_ref()),
688        ) {
689            (Some(style), _) | (None, Some(style)) => style,
690            (None, None) => {
691                theme_style = TextViewStyle::from_theme(&crate::Theme::global(cx));
692                &theme_style
693            }
694        };
695        // Follow the text color the container sets for its surface, so rich
696        // text stays readable in a filled bubble or a selected row.
697        let surface_style;
698        let mut on_inverted_surface = false;
699        if self.text_view_style.is_none() && defaults.is_some_and(|d| d.inherit_text_color) {
700            let color = self
701                .style
702                .text
703                .as_ref()
704                .and_then(|text| text.color)
705                .unwrap_or_else(|| window.text_style().color);
706            if color != text_view_style.foreground() {
707                on_inverted_surface = text_view_style.is_inverted_by(color);
708                surface_style = text_view_style.on_text_color(color);
709                text_view_style = &surface_style;
710            }
711        }
712        let inline_style;
713        if let Some(refinement) = &self.inline_code_style {
714            let mut style = text_view_style.inline_code_style().clone();
715            crate::refine_style_refinement(&mut style, refinement);
716            inline_style = text_view_style.clone().with_inline_code_style(style);
717            text_view_style = &inline_style;
718        }
719        let block_style;
720        if self.list_style.is_some() || self.blockquote_style.is_some() {
721            let mut style = text_view_style.clone();
722            if let Some(refinement) = &self.list_style {
723                let mut marker = style.list_style().clone();
724                crate::refine_style_refinement(&mut marker, refinement);
725                style = style.with_list_style(marker);
726            }
727            if let Some(refinement) = &self.blockquote_style {
728                let mut quote = style.blockquote_style().clone();
729                crate::refine_style_refinement(&mut quote, refinement);
730                style = style.with_blockquote_style(quote);
731            }
732            block_style = style;
733            text_view_style = &block_style;
734        }
735        let foreground = text_view_style.foreground();
736        let text_view_style = (*state.read(cx).text_view_style != *text_view_style)
737            .then(|| Arc::new(text_view_style.clone()));
738        let code_block_highlighter = self.code_block_highlighter.clone().or_else(|| {
739            defaults
740                .filter(|_| !on_inverted_surface)
741                .and_then(|d| d.code_block_highlighter.clone())
742        });
743
744        state.update(cx, |state, cx| {
745            if text_view_style.is_some()
746                || match (&state.code_block_highlighter, &code_block_highlighter) {
747                    (Some(previous), Some(next)) => !Arc::ptr_eq(previous, next),
748                    (None, None) => false,
749                    _ => true,
750                }
751            {
752                state.preserve_selection_for_reflow();
753            }
754            state.code_block_actions = self.code_block_actions.clone();
755            state.code_block_highlighter = code_block_highlighter;
756            state.table_actions = self.table_actions.clone();
757            state.link_click_handler = self.link_click_handler.clone();
758            state.image_source = self.image_source.clone();
759            state.set_markdown_extensions(self.markdown_extensions.clone(), cx);
760            if let Some(motion) = &self.motion {
761                state.set_motion(motion.clone());
762            }
763            state.selectable = self.selectable;
764            state.selection_format = self.selection_format;
765            state.scrollable = self.scrollable;
766            state.max_lines = max_lines;
767            if let Some(text_view_style) = text_view_style {
768                state.text_view_style = text_view_style;
769            }
770
771            if let Some(text) = &self.text {
772                state.set_element_text(text, cx);
773            }
774        });
775
776        let focus_handle = state.read(cx).focus_handle.clone();
777        let list_state = state.read(cx).list_state.clone();
778        // Cap the box at `n` body-text lines (the effective text style may be
779        // refined by this view's own style, e.g. `.text_sm()`); hidden
780        // overflow also clips descendant hitboxes to the box during prepaint.
781        let max_lines_cap = max_lines.map(|max_lines| {
782            let mut text_style = window.text_style();
783            if let Some(text) = &self.style.text {
784                text_style.refine(text);
785            }
786            text_style.line_height_in_pixels(window.rem_size()) * max_lines as f32
787        });
788
789        let mut el = div()
790            .id(("text-view-scroll", state.entity_id()))
791            .key_context("TextView")
792            .track_focus(&focus_handle)
793            .when(self.scrollable, |this| this.size_full())
794            .when_some(max_lines_cap, |this, cap| this.max_h(cap).overflow_hidden())
795            .relative()
796            .text_color(foreground)
797            .on_action(move |_: &crate::input::Copy, window, cx| {
798                let text = TextSelection::selected_text(window, cx).trim().to_string();
799                if text.is_empty() {
800                    cx.propagate();
801                    return;
802                }
803                cx.write_to_clipboard(wgpui::ClipboardItem::new_string(text));
804            })
805            .on_action(window.listener_for(&state, TextViewState::on_action_select_all))
806            .map(|this| {
807                if self.scrollable {
808                    this.child(crate::ScrollBounce::new(
809                        ("text-view-bounce", state.entity_id()),
810                        &list_state,
811                        state.clone(),
812                    ))
813                } else {
814                    this.child(state.clone())
815                }
816            })
817            // Overlay controls must paint after the document, otherwise rich
818            // content and selection backgrounds cover the thumb and hitbox.
819            .when(self.scrollable, |this| {
820                this.child(
821                    div().absolute().inset_0().child(
822                        crate::Scrollbar::vertical(&list_state)
823                            .id(("text-view-scrollbar", state.entity_id()))
824                            .viewport_from_layout(),
825                    ),
826                )
827            })
828            .refine_style(&self.style)
829            .into_any_element();
830        let layout_id = el.request_layout(window, cx);
831        (layout_id, TextViewLayoutState { state, element: el })
832    }
833
834    fn prepaint(
835        &mut self,
836        _: Option<&GlobalElementId>,
837        _: Option<&InspectorElementId>,
838        bounds: Bounds<Pixels>,
839        request_layout: &mut Self::RequestLayoutState,
840        window: &mut Window,
841        cx: &mut App,
842    ) -> Self::PrepaintState {
843        let state = request_layout.state.clone();
844        let max_lines_active = state.read(cx).max_lines.is_some();
845        if max_lines_active {
846            if let Ok(mut line_spans) = state.read(cx).line_spans.lock() {
847                line_spans.clear();
848            }
849        }
850        // Descendants read the view through the state stack during prepaint
851        // (in addition to the paint-time push below): `Inline`s report their
852        // line spans when `max_lines` is set, and table cells look for the
853        // selection anchor.
854        GlobalState::global(cx).push_text_view_state(state.clone());
855        request_layout.element.prepaint(window, cx);
856        GlobalState::global(cx).pop_text_view_state();
857
858        let mut clip_bottom = None;
859        if max_lines_active {
860            let (line_spans, content_bottom) = {
861                let state = state.read(cx);
862                (
863                    state
864                        .line_spans
865                        .lock()
866                        .map(|spans| spans.clone())
867                        .unwrap_or_default(),
868                    state.bounds().bottom(),
869                )
870            };
871            // The content keeps its natural height inside the capped box, so
872            // this sees everything the box cannot show — including a tall image
873            // that reports no lines of its own.
874            let clipped = content_bottom > bounds.bottom() + px(1.);
875            // Notify on change so observers (e.g. an "expand" button gated on
876            // `is_clamped`) re-render once the flag flips.
877            if state.read(cx).clamped != clipped {
878                state.update(cx, |state, cx| {
879                    state.clamped = clipped;
880                    cx.notify();
881                });
882            }
883            if clipped {
884                clip_bottom = line_safe_clip_bottom(&line_spans, bounds.bottom(), content_bottom);
885            }
886        }
887
888        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
889        // Over the text, so after its hitbox.
890        let touch_handles = if self.selectable {
891            state
892                .read(cx)
893                .selection_adapter
894                .prepaint_touch_handles(window, cx)
895        } else {
896            crate::TouchHandleLayout::default()
897        };
898        TextViewPrepaintState {
899            hitbox,
900            clip_bottom,
901            touch_handles,
902        }
903    }
904
905    fn paint(
906        &mut self,
907        _: Option<&GlobalElementId>,
908        _: Option<&InspectorElementId>,
909        bounds: Bounds<Pixels>,
910        request_layout: &mut Self::RequestLayoutState,
911        prepaint: &mut Self::PrepaintState,
912        window: &mut Window,
913        cx: &mut App,
914    ) {
915        let state = &request_layout.state;
916        if self.selectable {
917            state.read(cx).selection_adapter.begin_frame();
918        }
919
920        GlobalState::global(cx).push_text_view_state(state.clone());
921        if let Some(clip_bottom) = prepaint.clip_bottom {
922            // Snap the `max_lines` clip to the last whole line that fits, so a
923            // line of glyphs is never cut in half.
924            let mask = ContentMask {
925                bounds: Bounds::from_corners(bounds.origin, point(bounds.right(), clip_bottom)),
926            };
927            window.with_content_mask(Some(mask), |window| {
928                request_layout.element.paint(window, cx);
929            });
930        } else {
931            request_layout.element.paint(window, cx);
932        }
933        GlobalState::global(cx).pop_text_view_state();
934
935        // Every list has scrolled by now, so the line of a reveal is where
936        // it ends up this frame.
937        if state.read(cx).pending_reveal.is_some() {
938            let progress = state.update(cx, |state, _| {
939                state.pending_reveal.as_mut().map(PendingReveal::progress)
940            });
941            match progress {
942                Some(RevealProgress::Shown) => {
943                    state.update(cx, |state, _| state.pending_reveal = None);
944                }
945                Some(RevealProgress::Hidden(line)) => {
946                    if let Some(handler) = &self.reveal_handler {
947                        handler(line, window, cx);
948                    }
949                }
950                Some(RevealProgress::NotLaidOut) | None => {}
951            }
952        }
953
954        if self.selectable {
955            let (adapter, scroll_offset, content_bounds, self_scroll, handle_color) = {
956                let state = state.read(cx);
957                (
958                    state.selection_adapter.clone(),
959                    state.scroll_offset(),
960                    state.bounds(),
961                    state.scrollable,
962                    state.text_view_style.selection().alpha(1.),
963                )
964            };
965            adapter.register(
966                prepaint.hitbox.clone(),
967                content_bounds,
968                scroll_offset,
969                self_scroll,
970                window,
971                cx,
972            );
973            // The handles of a touch selection go over the text, and under
974            // whatever is painted over the text after it.
975            adapter.paint_touch_handles(&prepaint.touch_handles, handle_color, window, cx);
976        }
977    }
978}
979
980#[cfg(test)]
981mod tests {
982    use std::sync::{
983        Arc,
984        atomic::{AtomicUsize, Ordering},
985    };
986
987    use super::{TextView, TextViewPlugin};
988    use crate::text::{SelectionFormat, TableData, TextViewState, TextViewStyle};
989    use wgpui::{
990        AppContext as _, Bounds, ClickEvent, Context, Entity, InteractiveElement as _, IntoElement,
991        Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Overflow, ParentElement as _, Pixels,
992        Render, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
993        TestAppContext, VisualTestContext, Window, div, point, prelude::FluentBuilder as _, px,
994        rems,
995    };
996
997    struct TextViewTestRoot {
998        text_view: Entity<TextViewState>,
999    }
1000
1001    struct InlineHoverTestRoot {
1002        view: Entity<TextViewState>,
1003        builds: Arc<AtomicUsize>,
1004        format: crate::text::SelectionFormat,
1005    }
1006
1007    struct InlineHoverCard;
1008    impl Render for InlineHoverCard {
1009        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1010            div()
1011                .debug_selector(|| "inline-test-card".into())
1012                .w(px(120.))
1013                .h(px(40.))
1014                .child("Member profile")
1015        }
1016    }
1017
1018    impl Render for InlineHoverTestRoot {
1019        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1020            let builds = self.builds.clone();
1021            div()
1022                .pl(px(150.))
1023                .w(px(300.))
1024                .text_size(px(16.))
1025                .child(crate::TextSelectionLayer)
1026                .child(
1027                    TextView::new(&self.view)
1028                        .selection_format(self.format)
1029                        .plugin(
1030                            crate::text::markdown_ext::TestInlinePlugin::new("mention")
1031                                .parse_with(|node, _| {
1032                                    let markdown::mdast::Node::Link(link) = node else {
1033                                        return None;
1034                                    };
1035                                    let handle = link.url.strip_prefix("mention:")?;
1036                                    Some(
1037                                        crate::text::MarkdownNode::new("mention", ())
1038                                            .text(format!("@{handle}")),
1039                                    )
1040                                })
1041                                .render_with(move |_, _, _, _| {
1042                                    let builds = builds.clone();
1043                                    Some(crate::text::InlineElement::new(
1044                                        crate::HoverCard::new("mention-hover")
1045                                            .anchor(wgpui::Anchor::TopCenter)
1046                                            .trigger(div().child("@member"))
1047                                            .content(move |_, _, cx| {
1048                                                builds.fetch_add(1, Ordering::Relaxed);
1049                                                div()
1050                                                    .id("hover-content")
1051                                                    .child(cx.new(|_| InlineHoverCard))
1052                                            }),
1053                                    ))
1054                                }),
1055                        ),
1056                )
1057        }
1058    }
1059
1060    #[wgpui::test]
1061    fn text_view_follows_the_text_color_of_its_container(cx: &mut TestAppContext) {
1062        struct Root {
1063            inherited: Entity<TextViewState>,
1064            explicit: Entity<TextViewState>,
1065            surface_text: wgpui::Hsla,
1066        }
1067        impl Render for Root {
1068            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1069                div()
1070                    .w(px(300.))
1071                    .text_color(crate::ColorTokens::light().foreground)
1072                    .child(
1073                        div()
1074                            .text_color(self.surface_text)
1075                            .child(TextView::new(&self.inherited))
1076                            .child(TextView::new(&self.explicit).style(TextViewStyle::default())),
1077                    )
1078            }
1079        }
1080
1081        let colors = crate::ColorTokens::light();
1082        cx.update(|cx| {
1083            crate::init(cx);
1084            super::TextViewDefaults::new()
1085                .with_style(TextViewStyle::default())
1086                .with_inherit_text_color(true)
1087                .install(cx);
1088        });
1089        let (root, cx) = cx.add_window_view(|_, cx| Root {
1090            inherited: cx.new(|cx| TextViewState::markdown("[link](https://a.b) `code`", cx)),
1091            explicit: cx.new(|cx| TextViewState::markdown("text", cx)),
1092            surface_text: colors.primary_foreground,
1093        });
1094        cx.run_until_parked();
1095        cx.update(|window, cx| {
1096            window.draw(cx).clear();
1097        });
1098
1099        root.read_with(cx, |root, cx| {
1100            let inherited = &root.inherited.read(cx).text_view_style;
1101            assert_eq!(inherited.foreground(), colors.primary_foreground);
1102            assert_eq!(inherited.link(), colors.primary_foreground);
1103            assert!(inherited.is_dark());
1104
1105            let explicit = &root.explicit.read(cx).text_view_style;
1106            assert_eq!(explicit.foreground(), colors.foreground);
1107            assert_eq!(explicit.link(), TextViewStyle::default().link());
1108        });
1109    }
1110
1111    #[wgpui::test]
1112    fn inline_plugin_reuses_render_and_preserves_native_child_events(cx: &mut TestAppContext) {
1113        use std::sync::Mutex;
1114        struct ControlPlugin(Arc<Mutex<Vec<String>>>);
1115        impl crate::text::MarkdownPlugin for ControlPlugin {
1116            fn name(&self) -> &str {
1117                "control"
1118            }
1119            fn parse(
1120                &self,
1121                node: &markdown::mdast::Node,
1122                _: &crate::text::MarkdownParseContext<'_>,
1123            ) -> Option<crate::text::MarkdownNode> {
1124                let markdown::mdast::Node::Link(link) = node else {
1125                    return None;
1126                };
1127                let label = link.url.strip_prefix("control:")?;
1128                Some(crate::text::MarkdownNode::new("control", ()).text(label.to_string()))
1129            }
1130            fn render(
1131                &self,
1132                node: &crate::text::MarkdownNode,
1133                _: &mut Window,
1134                _: &mut wgpui::App,
1135            ) -> impl IntoElement {
1136                let clicks = self.0.clone();
1137                let label = node.as_text().to_string();
1138                div()
1139                    .id("same-control-id")
1140                    .w(px(60.))
1141                    .h(px(24.))
1142                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1143                    .on_click(move |_, _, _| clicks.lock().unwrap().push(label.clone()))
1144                    .child(node.as_text().to_string())
1145            }
1146        }
1147        struct Root {
1148            view: Entity<TextViewState>,
1149            clicks: Arc<Mutex<Vec<String>>>,
1150        }
1151        impl Render for Root {
1152            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1153                div()
1154                    .w(px(300.))
1155                    .child(crate::TextSelectionLayer)
1156                    .child(TextView::new(&self.view).plugin(ControlPlugin(self.clicks.clone())))
1157            }
1158        }
1159        cx.update(crate::init);
1160        let clicks = Arc::new(Mutex::new(Vec::new()));
1161        let captured = clicks.clone();
1162        let (root, cx) = cx.add_window_view(move |_, cx| Root {
1163            view: cx.new(|cx| TextViewState::markdown("[one](control:one)[two](control:two)", cx)),
1164            clicks,
1165        });
1166        cx.run_until_parked();
1167        cx.update(|window, cx| {
1168            window.draw(cx).clear();
1169        });
1170        let bounds = root.read_with(cx, |root, cx| {
1171            root.view.read(cx).selection_adapter.text_bounds()
1172        });
1173        assert_eq!(bounds.len(), 2);
1174        for bounds in bounds {
1175            cx.simulate_click(bounds.center(), Modifiers::default());
1176            cx.update(|window, cx| {
1177                window.draw(cx).clear();
1178            });
1179        }
1180        assert_eq!(*captured.lock().unwrap(), vec!["one", "two"]);
1181    }
1182
1183    #[wgpui::test]
1184    fn inline_hover_card_is_lazy_and_retains_atomic_copy(cx: &mut TestAppContext) {
1185        cx.update(crate::init);
1186        let builds = Arc::new(AtomicUsize::new(0));
1187        let source = "[@member](mention:member)";
1188        let (root, cx) = cx.add_window_view(|_, cx| InlineHoverTestRoot {
1189            view: cx.new(|cx| TextViewState::markdown(source, cx)),
1190            builds: builds.clone(),
1191            format: crate::text::SelectionFormat::Plain,
1192        });
1193        cx.run_until_parked();
1194        cx.update(|window, cx| window.draw(cx).clear());
1195        assert_eq!(builds.load(Ordering::Relaxed), 0);
1196        let view = root.read_with(cx, |root, _| root.view.clone());
1197        let bounds = view.read_with(cx, |view, _| view.selection_adapter.text_bounds()[0]);
1198        cx.update(|window, cx| {
1199            window.simulate_mouse_move(point(bounds.right() - px(1.), bounds.center().y), cx)
1200        });
1201        cx.run_until_parked();
1202        cx.executor()
1203            .advance_clock(std::time::Duration::from_secs(1));
1204        cx.run_until_parked();
1205        cx.update(|window, cx| window.draw(cx).clear());
1206        assert!(
1207            builds.load(Ordering::Relaxed) > 0,
1208            "hover did not build the card"
1209        );
1210        cx.update(|window, cx| window.draw(cx).clear());
1211        let card = cx
1212            .debug_bounds("inline-test-card")
1213            .expect("hover card should be painted");
1214        assert!(
1215            (card.center().x - bounds.center().x).abs() < px(1.),
1216            "card {card:?} must be centered on mention {bounds:?}"
1217        );
1218        assert!(
1219            card.top() >= bounds.bottom(),
1220            "card should be below the mention"
1221        );
1222        for (format, expected) in [
1223            (crate::text::SelectionFormat::Plain, "@member"),
1224            (crate::text::SelectionFormat::Source, source),
1225        ] {
1226            root.update(cx, |root, cx| {
1227                root.format = format;
1228                cx.notify();
1229            });
1230            view.update(cx, |view, cx| {
1231                view.set_selection_format(format, cx);
1232                view.select_all(cx);
1233            });
1234            cx.update(|window, cx| window.draw(cx).clear());
1235            assert_eq!(
1236                view.read_with(cx, |view, _| view.selected_text()).trim(),
1237                expected
1238            );
1239        }
1240    }
1241
1242    struct InlinePluginTestRoot {
1243        text_view: Entity<TextViewState>,
1244        width: Pixels,
1245        font_size: Pixels,
1246        source_format: bool,
1247        prepared_size: Option<Arc<AtomicUsize>>,
1248    }
1249
1250    impl Render for InlinePluginTestRoot {
1251        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1252            let prepared_size = self.prepared_size.clone();
1253            div().w(self.width).text_size(self.font_size).child(crate::TextSelectionLayer).child(
1254                TextView::new(&self.text_view)
1255                    .selection_format(if self.source_format { crate::text::SelectionFormat::Source }
1256                        else { crate::text::SelectionFormat::Plain })
1257
1258                    .plugin(crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(|node, _| {
1259                        let markdown::mdast::Node::InlineMath(math) = node else { return None };
1260                        Some(crate::text::MarkdownNode::new("math", ()).text(format!("{}²", math.value)))
1261                    }).render_with(move |_, context, _, _| {
1262                        let value = prepared_size.as_ref()?.load(Ordering::Relaxed) as f32;
1263                        let image = Arc::new(wgpui::Image::from_bytes(wgpui::ImageFormat::Svg,
1264                            b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"40\"><path d=\"M0 0L40 40\" stroke=\"black\"/></svg>".to_vec()));
1265                        let unit = context.font_size() / 16.;
1266                        Some(crate::text::InlineElement::new(wgpui::img(image).w(unit * value).h(unit * value)).with_baseline(unit * value * 0.75))
1267                    })))
1268        }
1269    }
1270
1271    #[wgpui::test]
1272    fn inline_plugins_drag_and_copy_across_formulas_in_both_directions(cx: &mut TestAppContext) {
1273        cx.update(crate::init);
1274        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1275            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1276            width: px(420.),
1277            font_size: px(16.),
1278            source_format: false,
1279            prepared_size: None,
1280        });
1281        let cx: &mut VisualTestContext = cx;
1282        for font_size in [16., 24., 32.] {
1283            for width in [60., 160., 420.] {
1284                for prepared in [None, Some(32)] {
1285                    for source_format in [false, true] {
1286                        root.update(cx, |root, cx| {
1287                            root.source_format = source_format;
1288                            root.width = px(width);
1289                            root.font_size = px(font_size);
1290                            root.prepared_size =
1291                                prepared.map(|value| Arc::new(AtomicUsize::new(value)));
1292                            cx.notify();
1293                        });
1294                        cx.run_until_parked();
1295                        cx.update(|window, cx| window.draw(cx).clear());
1296                        let bounds =
1297                            root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1298                        let text_bounds = root.read_with(cx, |root, cx| {
1299                            root.text_view.read(cx).selection_adapter.text_bounds()
1300                        });
1301                        let first = text_bounds.first().unwrap();
1302                        let last = text_bounds.last().unwrap();
1303                        let left =
1304                            point(first.left() + px(0.1), first.top() + first.size.height / 2.);
1305                        let right =
1306                            point(last.right() - px(0.1), last.top() + last.size.height / 2.);
1307                        for (start, end) in [(left, right), (right, left)] {
1308                            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1309                            cx.update(|window, cx| window.draw(cx).clear());
1310                            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1311                            cx.update(|window, cx| window.draw(cx).clear());
1312                            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1313                            cx.update(|window, cx| window.draw(cx).clear());
1314                            let selected = root
1315                                .read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1316                            assert_eq!(
1317                                selected.trim(),
1318                                if source_format {
1319                                    "中文 $x$ $y$ English"
1320                                } else {
1321                                    "中文 x² y² English"
1322                                },
1323                                "start={start:?} end={end:?} bounds={bounds:?} width={width} font_size={font_size} prepared={prepared:?}"
1324                            );
1325                        }
1326                    }
1327                }
1328            }
1329        }
1330    }
1331
1332    #[wgpui::test]
1333    fn inline_resource_size_update_reflows_without_changing_selection(cx: &mut TestAppContext) {
1334        cx.update(crate::init);
1335        let prepared_size = Arc::new(AtomicUsize::new(16));
1336        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1337            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1338            width: px(160.),
1339            font_size: px(16.),
1340            source_format: false,
1341            prepared_size: Some(prepared_size.clone()),
1342        });
1343        let cx: &mut VisualTestContext = cx;
1344        cx.run_until_parked();
1345        cx.update(|window, cx| window.draw(cx).clear());
1346        let before = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1347        let regions = root.read_with(cx, |root, cx| {
1348            root.text_view.read(cx).selection_adapter.text_bounds()
1349        });
1350        let first = regions.first().unwrap();
1351        let last = regions.last().unwrap();
1352        let start = point(first.left() + px(0.1), first.top() + px(10.));
1353        let end = point(last.right() - px(0.1), last.top() + px(10.));
1354        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1355        cx.update(|window, cx| window.draw(cx).clear());
1356        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1357        cx.update(|window, cx| window.draw(cx).clear());
1358        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1359        cx.update(|window, cx| window.draw(cx).clear());
1360        assert_eq!(
1361            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1362                .trim(),
1363            "中文 x² y² English"
1364        );
1365        prepared_size.store(100, Ordering::Relaxed);
1366        root.update(cx, |root, cx| {
1367            root.text_view
1368                .update(cx, |state, cx| state.invalidate_inline_layout(cx))
1369        });
1370        cx.run_until_parked();
1371        cx.update(|window, cx| window.draw(cx).clear());
1372        let after = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1373        assert!(after.size.height > before.size.height * 2.);
1374        assert_eq!(
1375            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1376                .trim(),
1377            "中文 x² y² English"
1378        );
1379    }
1380
1381    #[wgpui::test]
1382    fn triple_click_on_formula_selects_its_entire_mixed_line(cx: &mut TestAppContext) {
1383        cx.update(crate::init);
1384        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1385            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1386            width: px(420.),
1387            font_size: px(16.),
1388            source_format: false,
1389            prepared_size: None,
1390        });
1391        let cx: &mut VisualTestContext = cx;
1392        cx.run_until_parked();
1393        cx.update(|window, cx| window.draw(cx).clear());
1394        let regions = root.read_with(cx, |root, cx| {
1395            root.text_view.read(cx).selection_adapter.text_bounds()
1396        });
1397        let formula = regions[1];
1398        let position = formula.center();
1399        cx.simulate_event(MouseDownEvent {
1400            position,
1401            modifiers: Modifiers::default(),
1402            button: MouseButton::Left,
1403            click_count: 3,
1404            first_mouse: false,
1405        });
1406        cx.simulate_event(MouseUpEvent {
1407            position,
1408            modifiers: Modifiers::default(),
1409            button: MouseButton::Left,
1410            click_count: 3,
1411        });
1412        cx.update(|window, cx| window.draw(cx).clear());
1413        assert_eq!(
1414            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1415                .trim(),
1416            "before x² after"
1417        );
1418        root.update(cx, |root, cx| {
1419            root.source_format = true;
1420            cx.notify();
1421        });
1422        cx.update(|window, cx| window.draw(cx).clear());
1423        assert_eq!(
1424            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1425                .trim(),
1426            "before $x$ after"
1427        );
1428    }
1429
1430    #[wgpui::test]
1431    fn double_click_on_formula_selects_only_that_object(cx: &mut TestAppContext) {
1432        cx.update(crate::init);
1433        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1434            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1435            width: px(420.),
1436            font_size: px(16.),
1437            source_format: false,
1438            prepared_size: None,
1439        });
1440        let cx: &mut VisualTestContext = cx;
1441        cx.run_until_parked();
1442        cx.update(|window, cx| window.draw(cx).clear());
1443        let regions = root.read_with(cx, |root, cx| {
1444            root.text_view.read(cx).selection_adapter.text_bounds()
1445        });
1446        let position = regions[1].center();
1447        cx.simulate_event(MouseDownEvent {
1448            position,
1449            modifiers: Modifiers::default(),
1450            button: MouseButton::Left,
1451            click_count: 2,
1452            first_mouse: false,
1453        });
1454        cx.simulate_event(MouseUpEvent {
1455            position,
1456            modifiers: Modifiers::default(),
1457            button: MouseButton::Left,
1458            click_count: 2,
1459        });
1460        cx.update(|window, cx| window.draw(cx).clear());
1461        // Two clicks stop at the object; only three take the whole line.
1462        assert_eq!(
1463            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1464                .trim(),
1465            "x²"
1466        );
1467    }
1468
1469    /// A scrollable viewport, so the list has a bounded height to measure
1470    /// against and `max_offset_for_scrollbar` reports a real scroll extent.
1471    struct ScrollExtentTestRoot {
1472        text_view: Entity<TextViewState>,
1473    }
1474
1475    impl Render for ScrollExtentTestRoot {
1476        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1477            div()
1478                .w(px(400.))
1479                .h(px(200.))
1480                .overflow_hidden()
1481                .child(TextView::new(&self.text_view).scrollable(true))
1482        }
1483    }
1484
1485    /// `count` paragraphs, each `words` words long, so two documents can share
1486    /// a block count while differing wildly in height.
1487    fn document_of(count: usize, words: usize) -> String {
1488        (1..=count)
1489            .map(|i| format!("Block {i}: {}", "lorem ipsum dolor ".repeat(words)))
1490            .collect::<Vec<_>>()
1491            .join("\n\n")
1492    }
1493
1494    /// Replacing a document with one that happens to have the *same* block
1495    /// count must still re-measure. `Document::render_root` only resets the
1496    /// list when the count changes, so without an explicit re-measure every
1497    /// cached height stays with the previous document and the scroll extent
1498    /// keeps describing it.
1499    #[wgpui::test]
1500    fn replacing_a_document_with_an_equal_block_count_remeasures(cx: &mut TestAppContext) {
1501        cx.update(crate::init);
1502
1503        const BLOCKS: usize = 24;
1504        let short = document_of(BLOCKS, 1);
1505        let tall = document_of(BLOCKS, 60);
1506
1507        let (root, cx) = cx.add_window_view(|_, cx| ScrollExtentTestRoot {
1508            text_view: cx.new(|cx| TextViewState::markdown(&short, cx)),
1509        });
1510        let cx: &mut VisualTestContext = cx;
1511
1512        // The list is populated and measured during layout, so every
1513        // assertion below has to follow a real frame.
1514        let settle = |cx: &mut VisualTestContext| {
1515            cx.run_until_parked();
1516            cx.update(|window, cx| window.draw(cx).clear());
1517            cx.run_until_parked();
1518        };
1519        settle(cx);
1520
1521        let scroll_extent = |cx: &mut VisualTestContext| {
1522            root.read_with(cx, |root, cx| {
1523                root.text_view
1524                    .read(cx)
1525                    .list_state()
1526                    .max_offset_for_scrollbar()
1527                    .height
1528            })
1529        };
1530
1531        let short_extent = scroll_extent(cx);
1532
1533        root.update(cx, |root, cx| {
1534            root.text_view
1535                .update(cx, |state, cx| state.set_text(&tall, cx));
1536        });
1537        settle(cx);
1538
1539        root.read_with(cx, |root, cx| {
1540            assert_eq!(
1541                root.text_view.read(cx).list_state().item_count(),
1542                BLOCKS,
1543                "the replacement must keep the block count, or the list resets and the bug cannot occur"
1544            );
1545        });
1546
1547        let tall_extent = scroll_extent(cx);
1548        assert!(
1549            tall_extent > short_extent * 5.,
1550            "a much taller document must grow the scroll extent, but it went from \
1551             {short_extent:?} to {tall_extent:?}"
1552        );
1553    }
1554
1555    struct StatelessMarkdownRoot {
1556        renders: Arc<AtomicUsize>,
1557    }
1558
1559    impl Render for StatelessMarkdownRoot {
1560        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1561            self.renders.fetch_add(1, Ordering::Relaxed);
1562            div().child(
1563                TextView::markdown(
1564                    "stateless-markdown",
1565                    include_str!("../../tests/fixtures/upstream-readme.md"),
1566                )
1567                .markdown_block_parser(|_, _| None),
1568            )
1569        }
1570    }
1571
1572    struct DummyTextViewPlugin;
1573
1574    impl TextViewPlugin for DummyTextViewPlugin {
1575        fn setup(self, mut text_view: TextView) -> TextView {
1576            text_view.selectable = true;
1577            text_view
1578        }
1579    }
1580
1581    #[wgpui::test]
1582    fn text_view_constructors_are_selectable_by_default(cx: &mut TestAppContext) {
1583        cx.update(crate::init);
1584        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1585
1586        assert!(TextView::new(&state).selectable);
1587        assert!(TextView::markdown("markdown", "text").selectable);
1588        assert!(TextView::html("html", "<p>text</p>").selectable);
1589    }
1590
1591    #[wgpui::test]
1592    fn stateless_markdown_with_rebuilt_parser_settles(cx: &mut TestAppContext) {
1593        cx.update(crate::init);
1594        let renders = Arc::new(AtomicUsize::new(0));
1595        let (_, cx) = cx.add_window_view({
1596            let renders = renders.clone();
1597            move |_, _| StatelessMarkdownRoot { renders }
1598        });
1599        let cx: &mut VisualTestContext = cx;
1600
1601        cx.run_until_parked();
1602        cx.update(|window, cx| window.draw(cx).clear());
1603        let renders_after_redraw = renders.load(Ordering::Relaxed);
1604        cx.run_until_parked();
1605        assert_eq!(
1606            renders.load(Ordering::Relaxed),
1607            renders_after_redraw,
1608            "an unchanged TextView must not schedule another render after its parser is rebuilt",
1609        );
1610    }
1611
1612    #[wgpui::test]
1613    fn markdown_data_url_image_is_decoded_inline(cx: &mut TestAppContext) {
1614        use wgpui::{Image, ImageFormat, ImageSource};
1615
1616        // A 1x1 red PNG.
1617        const PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
1618
1619        cx.update(crate::init);
1620        let markdown = format!("Inline ![dot](data:image/png;base64,{PNG_BASE64}) image");
1621        let (_, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new(&markdown, cx));
1622        let cx: &mut VisualTestContext = cx;
1623
1624        cx.run_until_parked();
1625        cx.update(|window, cx| window.draw(cx).clear());
1626
1627        // `Image` keys the asset system by a hash of its bytes, so rebuilding it
1628        // from the same body finds the entry the text view's `img` registered
1629        // when it rendered — proof the body was decoded in place instead of
1630        // being fetched over HTTP.
1631        let bytes = data_url::DataUrl::process(&format!("data:image/png;base64,{PNG_BASE64}"))
1632            .unwrap()
1633            .decode_to_vec()
1634            .unwrap()
1635            .0;
1636        let image = Arc::new(Image::from_bytes(ImageFormat::Png, bytes));
1637        assert!(
1638            cx.update(|_, cx| ImageSource::Image(image).is_asset_cached(cx)),
1639            "the data URL image must be handed to GPUI as decoded bytes",
1640        );
1641    }
1642
1643    #[wgpui::test]
1644    fn unstyled_text_view_uses_base_tokens_for_link_and_input_selection(cx: &mut TestAppContext) {
1645        cx.update(crate::init);
1646        cx.update(|cx| {
1647            let colors = &mut crate::Theme::global_mut(cx).tokens.colors;
1648            colors.primary = wgpui::rgb(0x55aaff).into();
1649            colors.selection = wgpui::rgb(0x335577).into();
1650        });
1651        let (root, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new("[link](url)", cx));
1652        let cx: &mut VisualTestContext = cx;
1653
1654        cx.run_until_parked();
1655        root.read_with(cx, |root, cx| {
1656            let style = &root.text_view.read(cx).text_view_style;
1657            assert_eq!(style.link(), wgpui::rgb(0x55aaff).into());
1658            assert_eq!(style.selection(), wgpui::rgb(0x335577).into());
1659        });
1660    }
1661
1662    #[wgpui::test]
1663    fn inline_code_view_refinement_keeps_unspecified_style_properties(cx: &mut TestAppContext) {
1664        use super::{TextViewDefaults, TextViewStyle};
1665        struct StyledCode(Entity<TextViewState>);
1666        impl Render for StyledCode {
1667            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1668                TextView::new(&self.0)
1669                    .inline_code_style(
1670                        StyleRefinement::default()
1671                            .border_1()
1672                            .border_color(wgpui::blue())
1673                            .text_color(wgpui::blue()),
1674                    )
1675                    .into_any_element()
1676            }
1677        }
1678        cx.update(crate::init);
1679        cx.update(|cx| {
1680            cx.set_global(
1681                TextViewDefaults::default().with_style(
1682                    TextViewStyle::default().with_inline_code_style(
1683                        StyleRefinement::default()
1684                            .text_size(rems(1.))
1685                            .font_weight(wgpui::FontWeight::BOLD)
1686                            .bg(wgpui::red()),
1687                    ),
1688                ),
1689            )
1690        });
1691        let (root, cx) = cx.add_window_view(|_, cx| {
1692            StyledCode(cx.new(|cx| TextViewState::markdown("before `code` after", cx)))
1693        });
1694        cx.run_until_parked();
1695        cx.update(|window, cx| window.draw(cx).clear());
1696        root.read_with(cx, |root, cx| {
1697            let state = root.0.read(cx);
1698            let style = state.text_view_style.inline_code_style();
1699            assert_eq!(
1700                style.text.as_ref().and_then(|text| text.font_size),
1701                Some(rems(1.).into())
1702            );
1703            assert_eq!(
1704                style.text.as_ref().and_then(|text| text.font_weight),
1705                Some(wgpui::FontWeight::BOLD)
1706            );
1707            assert_eq!(
1708                style.text.as_ref().and_then(|text| text.color),
1709                Some(wgpui::blue())
1710            );
1711            assert_eq!(style.background, Some(wgpui::red().into()));
1712            assert_eq!(style.border_color, Some(wgpui::blue()));
1713            assert_eq!(style.border_widths.left, Some(px(1.).into()));
1714        });
1715    }
1716
1717    #[wgpui::test]
1718    fn list_and_blockquote_view_refinements_keep_unspecified_style_properties(
1719        cx: &mut TestAppContext,
1720    ) {
1721        use super::{TextViewDefaults, TextViewStyle};
1722        struct StyledBlocks(Entity<TextViewState>);
1723        impl Render for StyledBlocks {
1724            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1725                TextView::new(&self.0)
1726                    .list_style(StyleRefinement::default().text_color(wgpui::blue()))
1727                    .blockquote_style(StyleRefinement::default().border_color(wgpui::blue()))
1728                    .into_any_element()
1729            }
1730        }
1731        cx.update(crate::init);
1732        cx.update(|cx| {
1733            cx.set_global(
1734                TextViewDefaults::default().with_style(
1735                    TextViewStyle::default()
1736                        .with_list_style(
1737                            StyleRefinement::default().font_weight(wgpui::FontWeight::BOLD),
1738                        )
1739                        .with_blockquote_style(StyleRefinement::default().border_l_4()),
1740                ),
1741            )
1742        });
1743        let (root, cx) = cx.add_window_view(|_, cx| {
1744            StyledBlocks(cx.new(|cx| TextViewState::markdown("- item\n\n> quote", cx)))
1745        });
1746        cx.run_until_parked();
1747        cx.update(|window, cx| window.draw(cx).clear());
1748        root.read_with(cx, |root, cx| {
1749            let style = &root.0.read(cx).text_view_style;
1750            let marker = style.list_style();
1751            assert_eq!(
1752                marker.text.as_ref().and_then(|text| text.color),
1753                Some(wgpui::blue())
1754            );
1755            assert_eq!(
1756                marker.text.as_ref().and_then(|text| text.font_weight),
1757                Some(wgpui::FontWeight::BOLD)
1758            );
1759            let quote = style.blockquote_style();
1760            assert_eq!(quote.border_color, Some(wgpui::blue()));
1761            assert_eq!(quote.border_widths.left, Some(px(4.).into()));
1762        });
1763    }
1764
1765    impl TextViewTestRoot {
1766        fn new(text: &str, cx: &mut Context<Self>) -> Self {
1767            let text = text.to_string();
1768            let text_view = cx.new(|cx| TextViewState::markdown(&text, cx));
1769            Self { text_view }
1770        }
1771    }
1772
1773    impl Render for TextViewTestRoot {
1774        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1775            div()
1776                .w(px(160.))
1777                .child(
1778                    div()
1779                        .h(px(24.))
1780                        .overflow_hidden()
1781                        .child(TextView::new(&self.text_view).selectable(true)),
1782                )
1783                .child(div().h(px(40.)).child("footer"))
1784        }
1785    }
1786
1787    struct TableSelectionTestRoot {
1788        text_view: Entity<TextViewState>,
1789    }
1790
1791    impl Render for TableSelectionTestRoot {
1792        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1793            div()
1794                .debug_selector(|| "table-selection-root".into())
1795                .w(px(520.))
1796                .child(crate::TextSelectionLayer)
1797                .child(TextView::new(&self.text_view))
1798        }
1799    }
1800
1801    #[wgpui::test]
1802    fn table_drag_selection_settles_without_requesting_idle_frames(cx: &mut TestAppContext) {
1803        cx.update(crate::init);
1804        let (_, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
1805            text_view: cx.new(|cx| {
1806                TextViewState::markdown(
1807                    "| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
1808                    cx,
1809                )
1810            }),
1811        });
1812        let cx: &mut VisualTestContext = cx;
1813
1814        cx.run_until_parked();
1815        let bounds = cx
1816            .debug_bounds("table-selection-root")
1817            .expect("table bounds");
1818        let start = point(bounds.left() + px(24.), bounds.top() + px(16.));
1819        let end = point(bounds.right() - px(24.), bounds.bottom() - px(16.));
1820        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1821        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1822        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1823
1824        assert!(cx.update(|window, cx| crate::TextSelection::has_selection(window, cx)));
1825        assert_eq!(
1826            cx.update(|window, cx| window.simulate_next_frame(cx)),
1827            0,
1828            "finished table selection must not continuously request frames"
1829        );
1830    }
1831
1832    /// A drag that starts in a table cell selects only in that cell, also when
1833    /// the pointer leaves the cell. A drag that starts outside the table still
1834    /// selects through it.
1835    #[wgpui::test]
1836    fn table_drag_from_a_cell_stays_in_that_cell(cx: &mut TestAppContext) {
1837        cx.update(crate::init);
1838        let (root, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
1839            text_view: cx.new(|cx| {
1840                TextViewState::markdown(
1841                    "Intro\n\n| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
1842                    cx,
1843                )
1844            }),
1845        });
1846        let cx: &mut VisualTestContext = cx;
1847        cx.run_until_parked();
1848        cx.update(|window, cx| window.draw(cx).clear());
1849
1850        let text_bounds = root.read_with(cx, |root, cx| {
1851            root.text_view.read(cx).selection_adapter.text_bounds()
1852        });
1853        assert_eq!(text_bounds.len(), 7, "{text_bounds:?}");
1854        let [intro, _, _, cell_a, cell_b, _, cell_d] = text_bounds[..] else {
1855            unreachable!()
1856        };
1857        let table = cx
1858            .debug_bounds("table-selection-root")
1859            .expect("table bounds");
1860        let start_of = |bounds: Bounds<Pixels>| point(bounds.left() + px(0.1), bounds.center().y);
1861        let end_of = |bounds: Bounds<Pixels>| point(bounds.right() - px(0.1), bounds.center().y);
1862
1863        let mut drag = |start, end| {
1864            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1865            cx.update(|window, cx| window.draw(cx).clear());
1866            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1867            cx.update(|window, cx| window.draw(cx).clear());
1868            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1869            cx.update(|window, cx| window.draw(cx).clear());
1870            let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1871            let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
1872            (selected.trim().to_string(), copied.trim().to_string())
1873        };
1874
1875        // Down and right, out of the table: the rest of the cell, nothing else.
1876        let below = point(table.right() - px(2.), table.bottom() - px(1.));
1877        let expected = ("Cell A".to_string(), "Cell A".to_string());
1878        assert_eq!(drag(start_of(cell_a), below), expected);
1879
1880        // Back along its line into the cell before it, and up and out of the
1881        // table: the start of the cell, nothing else.
1882        let expected = ("Cell B".to_string(), "Cell B".to_string());
1883        let left = point(cell_a.center().x, cell_b.center().y);
1884        assert_eq!(drag(end_of(cell_b), left), expected);
1885        let above = point(table.left() + px(2.), intro.top());
1886        assert_eq!(drag(end_of(cell_b), above), expected);
1887
1888        // From the paragraph before the table, the selection goes through it.
1889        let (selected, copied) = drag(start_of(intro), end_of(cell_d));
1890        for text in ["Intro", "Header 1", "Cell A", "Cell B", "Cell C", "Cell D"] {
1891            assert!(selected.contains(text), "{text} not in {selected:?}");
1892            assert!(copied.contains(text), "{text} not in {copied:?}");
1893        }
1894
1895        // Copy before the frame that paints the last move: Copy projects the
1896        // selection itself and keeps it in the cell too.
1897        cx.simulate_mouse_down(start_of(cell_a), MouseButton::Left, Modifiers::default());
1898        cx.update(|window, cx| window.draw(cx).clear());
1899        cx.simulate_mouse_move(end_of(cell_a), MouseButton::Left, Modifiers::default());
1900        cx.update(|window, cx| window.draw(cx).clear());
1901        cx.simulate_mouse_move(below, MouseButton::Left, Modifiers::default());
1902        cx.simulate_mouse_up(below, MouseButton::Left, Modifiers::default());
1903        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
1904        assert_eq!(copied.trim(), "Cell A");
1905    }
1906
1907    struct CellSelectionTestRoot {
1908        text_view: Entity<TextViewState>,
1909        scrollable: bool,
1910    }
1911
1912    impl Render for CellSelectionTestRoot {
1913        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1914            div()
1915                .w(px(520.))
1916                .h(px(400.))
1917                .child(crate::TextSelectionLayer)
1918                .child(TextView::new(&self.text_view).scrollable(self.scrollable))
1919        }
1920    }
1921
1922    #[wgpui::test]
1923    fn table_cell_copy_excludes_following_blocks_in_a_scrollable_view(cx: &mut TestAppContext) {
1924        cx.update(crate::init);
1925        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
1926            text_view: cx.new(|cx| TextViewState::markdown(
1927                "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |\n\nMiddle paragraph\n\nLast paragraph", cx)),
1928            scrollable: true,
1929        });
1930        cx.run_until_parked();
1931        cx.update(|window, cx| window.draw(cx).clear());
1932        let rows = root.read_with(cx, |root, cx| {
1933            root.text_view.read(cx).selection_adapter.text_bounds()
1934        });
1935        assert_eq!(rows.len(), 6, "{rows:?}");
1936        let start = point(rows[2].left() + px(0.1), rows[2].center().y);
1937        let inside = point(rows[2].right() - px(0.1), rows[2].center().y);
1938        let end = point(rows[5].right() - px(0.1), rows[5].center().y);
1939        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1940        cx.simulate_mouse_move(inside, MouseButton::Left, Modifiers::default());
1941        cx.update(|window, cx| window.draw(cx).clear());
1942        // The copy callback must constrain the logical block range even before paint.
1943        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1944        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1945        for format in [SelectionFormat::Plain, SelectionFormat::Source] {
1946            root.update(cx, |root, cx| {
1947                root.text_view
1948                    .update(cx, |state, cx| state.set_selection_format(format, cx))
1949            });
1950            let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
1951            assert_eq!(copied.trim(), "Cell A", "{format:?}");
1952        }
1953        cx.update(|window, cx| window.draw(cx).clear());
1954        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1955        assert_eq!(selected.trim(), "Cell A");
1956    }
1957
1958    #[wgpui::test]
1959    fn table_cell_touch_select_all_includes_every_cell(cx: &mut TestAppContext) {
1960        cx.update(crate::init);
1961        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
1962            text_view: cx.new(|cx| {
1963                TextViewState::markdown(
1964                    "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
1965                    cx,
1966                )
1967            }),
1968            scrollable: false,
1969        });
1970        cx.run_until_parked();
1971        cx.update(|window, cx| window.draw(cx).clear());
1972        let rows = root.read_with(cx, |root, cx| {
1973            root.text_view.read(cx).selection_adapter.text_bounds()
1974        });
1975        let position = rows[2].center();
1976        for phase in [wgpui::TouchPhase::Started, wgpui::TouchPhase::Ended] {
1977            cx.simulate_event(wgpui::LongPressEvent {
1978                phase,
1979                start_position: position,
1980                position,
1981            });
1982        }
1983        cx.update(|window, cx| {
1984            window.draw(cx).clear();
1985            crate::TextSelection::select_all(window, cx);
1986            window.draw(cx).clear();
1987        });
1988        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
1989        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1990        for text in ["Header", "Other", "Cell A", "Cell B"] {
1991            assert!(selected.contains(text), "{selected:?}");
1992            assert!(copied.contains(text), "{copied:?}");
1993        }
1994    }
1995
1996    #[wgpui::test]
1997    fn table_cell_selection_does_not_leak_into_another_window(cx: &mut TestAppContext) {
1998        cx.update(crate::init);
1999        let start = {
2000            let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2001                text_view: cx.new(|cx| {
2002                    TextViewState::markdown(
2003                        "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
2004                        cx,
2005                    )
2006                }),
2007                scrollable: false,
2008            });
2009            cx.run_until_parked();
2010            cx.update(|window, cx| window.draw(cx).clear());
2011            let rows = root.read_with(cx, |root, cx| {
2012                root.text_view.read(cx).selection_adapter.text_bounds()
2013            });
2014            let start = point(rows[0].left() + px(0.1), rows[0].center().y);
2015            let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2016            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2017            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2018            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2019            cx.update(|window, cx| window.draw(cx).clear());
2020            assert_eq!(
2021                cx.update(|window, cx| crate::TextSelection::selected_text(window, cx))
2022                    .trim(),
2023                "Header"
2024            );
2025            start
2026        };
2027        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2028            text_view: cx.new(|cx| TextViewState::markdown("ordinary text in another window", cx)),
2029            scrollable: false,
2030        });
2031        cx.run_until_parked();
2032        cx.update(|window, cx| window.draw(cx).clear());
2033        let rows = root.read_with(cx, |root, cx| {
2034            root.text_view.read(cx).selection_adapter.text_bounds()
2035        });
2036        assert!(rows[0].contains(&start), "{start:?}, {rows:?}");
2037        let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2038        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2039        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2040        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2041        cx.update(|window, cx| window.draw(cx).clear());
2042        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2043        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2044        assert!(!selected.trim().is_empty());
2045        assert_eq!(copied, selected);
2046    }
2047
2048    struct InlineImageTextViewTestRoot {
2049        text_view: Entity<TextViewState>,
2050    }
2051
2052    impl InlineImageTextViewTestRoot {
2053        fn new(cx: &mut Context<Self>) -> Self {
2054            let text_view = cx.new(|cx| {
2055                TextViewState::markdown(
2056                    "Build Status ![inline image](https://example.com/image.svg) after",
2057                    cx,
2058                )
2059            });
2060            Self { text_view }
2061        }
2062    }
2063
2064    impl Render for InlineImageTextViewTestRoot {
2065        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2066            div()
2067                .w(px(420.))
2068                .child(TextView::new(&self.text_view).selectable(true))
2069        }
2070    }
2071
2072    #[wgpui::test]
2073    fn inline_image_keeps_surrounding_text_on_same_line(cx: &mut TestAppContext) {
2074        cx.update(crate::init);
2075        let (content, cx) = cx.add_window_view(|_, cx| InlineImageTextViewTestRoot::new(cx));
2076        let cx: &mut VisualTestContext = cx;
2077
2078        cx.run_until_parked();
2079        cx.update(|window, cx| {
2080            let _ = window.draw(cx);
2081        });
2082
2083        let inline_bounds = content.read_with(cx, |content, cx| {
2084            content.text_view.read(cx).selection_adapter.text_bounds()
2085        });
2086
2087        assert_eq!(inline_bounds.len(), 2);
2088        assert_eq!(
2089            inline_bounds[0].top(),
2090            inline_bounds[1].top(),
2091            "text before and after an inline image should share a rendered line"
2092        );
2093        assert!(
2094            inline_bounds[1].left() - inline_bounds[0].right() > px(8.),
2095            "inline image should reserve horizontal space in the text layout"
2096        );
2097        assert!(
2098            inline_bounds[1].left() - inline_bounds[0].right() < px(40.),
2099            "unloaded inline image fallback should stay generic and compact"
2100        );
2101    }
2102
2103    #[wgpui::test]
2104    fn inline_html_image_after_newline_does_not_panic(cx: &mut TestAppContext) {
2105        cx.update(crate::init);
2106        let (_, cx) = cx.add_window_view(|_, cx| {
2107            TextViewTestRoot::new(
2108                "Hi\n[<img src=\"https://example.com/image.svg\">](https://google.com/)",
2109                cx,
2110            )
2111        });
2112        let cx: &mut VisualTestContext = cx;
2113
2114        cx.run_until_parked();
2115        cx.update(|window, cx| {
2116            let _ = window.draw(cx);
2117        });
2118    }
2119
2120    #[wgpui::test]
2121    fn list_item_renders_fenced_code_block_at_document_width(cx: &mut TestAppContext) {
2122        struct ListItemBlockRoot;
2123
2124        impl Render for ListItemBlockRoot {
2125            fn render(
2126                &mut self,
2127                _window: &mut Window,
2128                _cx: &mut Context<Self>,
2129            ) -> impl IntoElement {
2130                div().w(px(840.)).h(px(400.)).child(
2131                    crate::h_resizable("markdown-width-test")
2132                        .child(crate::resizable_panel().child(div()))
2133                        .child(crate::resizable_panel().child(
2134                            TextView::markdown(
2135                                "list-with-code",
2136                                "1. List item\n   ```rust\n   nested code\n   ```\n\n```rust\ntop-level code\n```",
2137                            )
2138                            .code_block_actions(|code_block, _, _| {
2139                                let selector = if code_block.code().contains("nested") {
2140                                    "nested-code-action"
2141                                } else {
2142                                    "top-level-code-action"
2143                                };
2144                                div()
2145                                    .debug_selector(move || selector.into())
2146                                    .child("Copy")
2147                            })
2148                            .scrollable(true)
2149                            .p_5()
2150                            .flex_none(),
2151                        )),
2152                )
2153            }
2154        }
2155
2156        cx.update(crate::init);
2157        let (_, cx) = cx.add_window_view(|_, _| ListItemBlockRoot);
2158        let cx: &mut VisualTestContext = cx;
2159
2160        cx.run_until_parked();
2161        cx.update(|window, cx| {
2162            let _ = window.draw(cx);
2163        });
2164
2165        let nested_action = cx.debug_bounds("nested-code-action").unwrap();
2166        let top_level_action = cx.debug_bounds("top-level-code-action").unwrap();
2167        assert!(
2168            top_level_action.right() - nested_action.right() < px(32.),
2169            "nested code block should fill the list item's available width"
2170        );
2171    }
2172
2173    /// Height cap of the scrolling code block in [`ScrollingCodeRoot`].
2174    const CODE_HEIGHT: Pixels = px(60.);
2175
2176    struct ScrollingCodeRoot {
2177        text_view: Entity<TextViewState>,
2178        actions: bool,
2179    }
2180
2181    impl Render for ScrollingCodeRoot {
2182        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2183            let mut code_block = StyleRefinement::default().max_h(CODE_HEIGHT);
2184            code_block.overflow.y = Some(Overflow::Scroll);
2185
2186            div().w(px(320.)).h(px(200.)).child(
2187                TextView::new(&self.text_view)
2188                    .style(TextViewStyle::default().with_code_block(code_block))
2189                    .when(self.actions, |this| {
2190                        this.code_block_actions(|_, _, _| {
2191                            div().debug_selector(|| "code-action".into()).child("Copy")
2192                        })
2193                    })
2194                    .scrollable(true),
2195            )
2196        }
2197    }
2198
2199    #[wgpui::test]
2200    fn scrolling_code_block_keeps_wheel_from_the_list(cx: &mut TestAppContext) {
2201        cx.update(crate::init);
2202        let code = (0..50).map(|i| format!("line {i}\n")).collect::<String>();
2203        let tail = "Paragraph after the code.\n\n".repeat(20);
2204        let markdown = format!("```\n{code}```\n\n{tail}");
2205
2206        // Scrolling must not depend on `code_block_actions`, which is what
2207        // gives a non-scrolling block its id.
2208        for actions in [false, true] {
2209            let (root, cx) = cx.add_window_view(|_, cx| ScrollingCodeRoot {
2210                text_view: cx.new(|cx| TextViewState::markdown(&markdown, cx)),
2211                actions,
2212            });
2213            let cx: &mut VisualTestContext = cx;
2214            let draw = |cx: &mut VisualTestContext| {
2215                cx.run_until_parked();
2216                cx.update(|window, cx| window.draw(cx).clear());
2217            };
2218            let step = px(20.);
2219            let wheel_at = |cx: &mut VisualTestContext, y: Pixels| {
2220                cx.simulate_event(wgpui::ScrollEvent {
2221                    position: point(px(20.), y),
2222                    delta: wgpui::ScrollDelta::Pixels(point(px(0.), -step)),
2223                    ..Default::default()
2224                });
2225            };
2226            // The code block is first in the view, and painted lines are
2227            // clipped to its viewport: the first code line's bottom moves with
2228            // the code, the first line below the viewport moves with the list.
2229            let edges = |cx: &mut VisualTestContext| {
2230                let lines = root.read_with(cx, |root, cx| {
2231                    root.text_view.read(cx).selection_adapter.text_bounds()
2232                });
2233                let paragraph = lines.iter().find(|line| line.top() >= CODE_HEIGHT).unwrap();
2234                (lines[0].bottom(), paragraph.top())
2235            };
2236            draw(cx);
2237            let (code_bottom, paragraph_top) = edges(cx);
2238            let action = cx.debug_bounds("code-action");
2239
2240            // Over the code block: the code scrolls, the list and the pinned
2241            // actions stay put.
2242            wheel_at(cx, CODE_HEIGHT / 2.);
2243            draw(cx);
2244            assert_eq!(
2245                edges(cx),
2246                (code_bottom - step, paragraph_top),
2247                "actions: {actions}"
2248            );
2249            assert_eq!(cx.debug_bounds("code-action"), action);
2250
2251            // Below the code block the list still scrolls. Only inequality
2252            // holds: once the paragraph moves into the code's band, `edges`
2253            // picks the next one down.
2254            wheel_at(cx, CODE_HEIGHT * 2.5);
2255            draw(cx);
2256            assert_ne!(edges(cx).1, paragraph_top, "actions: {actions}");
2257        }
2258    }
2259
2260    /// Draw a Markdown table with a `table_actions` hook installed, and return
2261    /// the painted bounds of the actions element plus the data it received.
2262    /// `scroll` opts into the horizontally scrollable table layout.
2263    fn draw_table_with_actions(
2264        cx: &mut TestAppContext,
2265        scroll: bool,
2266    ) -> (Bounds<Pixels>, TableData) {
2267        use std::sync::{Arc, Mutex};
2268
2269        struct TableRoot {
2270            scroll: bool,
2271            captured: Arc<Mutex<Vec<TableData>>>,
2272        }
2273
2274        impl Render for TableRoot {
2275            fn render(
2276                &mut self,
2277                _window: &mut Window,
2278                _cx: &mut Context<Self>,
2279            ) -> impl IntoElement {
2280                let captured = self.captured.clone();
2281                let mut table_style = StyleRefinement::default();
2282                if self.scroll {
2283                    table_style.overflow.x = Some(Overflow::Scroll);
2284                }
2285
2286                div().w(px(320.)).child(
2287                    TextView::markdown(
2288                        "table-actions",
2289                        "| Name | Age |\n|:--|--:|\n| Alice | 30 |\n| Bob | 41 |",
2290                    )
2291                    .style(TextViewStyle::default().with_table(table_style))
2292                    .table_actions(move |table, _, _| {
2293                        if let Ok(mut captured) = captured.lock() {
2294                            captured.push(table.clone());
2295                        }
2296                        div().debug_selector(|| "table-action".into()).child("Copy")
2297                    }),
2298                )
2299            }
2300        }
2301
2302        cx.update(crate::init);
2303        let captured = Arc::new(Mutex::new(Vec::new()));
2304        let (_, cx) = cx.add_window_view({
2305            let captured = captured.clone();
2306            move |_, _| TableRoot { scroll, captured }
2307        });
2308        let cx: &mut VisualTestContext = cx;
2309
2310        cx.run_until_parked();
2311        cx.update(|window, cx| {
2312            let _ = window.draw(cx);
2313        });
2314
2315        let bounds = cx
2316            .debug_bounds("table-action")
2317            .expect("table actions should be painted");
2318        let data = captured
2319            .lock()
2320            .expect("captured table data")
2321            .last()
2322            .cloned()
2323            .expect("table actions hook should receive the table");
2324
2325        (bounds, data)
2326    }
2327
2328    #[wgpui::test]
2329    fn table_actions_render_below_the_table(cx: &mut TestAppContext) {
2330        for scroll in [false, true] {
2331            let (bounds, data) = draw_table_with_actions(cx, scroll);
2332
2333            // Header plus two data rows are painted above the actions row.
2334            assert!(
2335                bounds.top() > px(40.),
2336                "actions should sit below the table (scroll: {scroll}), got {:?}",
2337                bounds.top()
2338            );
2339            assert_eq!(data.headers, vec!["Name", "Age"]);
2340            assert_eq!(data.rows, vec![vec!["Alice", "30"], vec!["Bob", "41"]]);
2341            assert_eq!(
2342                data.markdown,
2343                "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n| Bob | 41 |"
2344            );
2345            assert_eq!(data.span, Some(0..52));
2346        }
2347    }
2348
2349    #[test]
2350    fn plugin_accepts_text_view_plugins_beyond_markdown() {
2351        let view = TextView::markdown("plugin-test", "").plugin(DummyTextViewPlugin);
2352
2353        assert!(view.selectable);
2354    }
2355
2356    #[test]
2357    fn syntax_highlighting_is_opt_in() {
2358        let default_view = TextView::markdown("default-code", "```rust\nfn main() {}\n```");
2359        assert!(default_view.code_block_highlighter.is_none());
2360
2361        let view = default_view.code_block_highlighter(|block| {
2362            vec![(
2363                0..block.code().len(),
2364                wgpui::HighlightStyle {
2365                    color: Some(wgpui::rgb(0x3366ff).into()),
2366                    ..Default::default()
2367                },
2368            )]
2369        });
2370        assert!(view.code_block_highlighter.is_some());
2371    }
2372
2373    #[wgpui::test]
2374    fn clipped_markdown_link_does_not_open(cx: &mut TestAppContext) {
2375        cx.update(crate::init);
2376        let (_, cx) = cx.add_window_view(|_, cx| {
2377            TextViewTestRoot::new("visible\n\n[hidden](https://example.com)", cx)
2378        });
2379        let cx: &mut VisualTestContext = cx;
2380
2381        cx.simulate_click(point(px(10.), px(34.)), Modifiers::default());
2382
2383        assert_eq!(cx.opened_url(), None);
2384    }
2385
2386    struct MaxLinesTestRoot {
2387        text_view: Entity<TextViewState>,
2388        max_lines: usize,
2389    }
2390
2391    impl MaxLinesTestRoot {
2392        fn new(text: &str, max_lines: usize, cx: &mut Context<Self>) -> Self {
2393            let text_view = cx.new(|cx| TextViewState::markdown(text, cx));
2394            Self {
2395                text_view,
2396                max_lines,
2397            }
2398        }
2399    }
2400
2401    impl Render for MaxLinesTestRoot {
2402        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2403            div()
2404                .w(px(200.))
2405                .child(TextView::new(&self.text_view).max_lines(self.max_lines))
2406        }
2407    }
2408
2409    #[test]
2410    fn the_clip_only_moves_for_a_straddling_glyph_line() {
2411        use super::line_safe_clip_bottom;
2412        use crate::text::state::LineSpan;
2413
2414        let spans = [
2415            // Lines end at 20 / 40 / 60.
2416            LineSpan {
2417                top: px(0.),
2418                bottom: px(60.),
2419                line_height: px(20.),
2420            },
2421            // A second block after an 8px gap; lines end at 88 / 108 / 128.
2422            LineSpan {
2423                top: px(68.),
2424                bottom: px(128.),
2425                line_height: px(20.),
2426            },
2427        ];
2428
2429        // Content continues well past the box in every case but the last.
2430        let below = px(400.);
2431
2432        // A box ending inside the line 88..108 leaves that line out whole.
2433        assert_eq!(
2434            line_safe_clip_bottom(&spans, px(100.), below),
2435            Some(px(88.))
2436        );
2437
2438        // A box ending on a line boundary has nothing to pull the clip up for.
2439        assert_eq!(line_safe_clip_bottom(&spans, px(88.), below), None);
2440
2441        // A strip below the last line shorter than a line — the border and
2442        // padding a block leads with — is not worth showing.
2443        assert_eq!(line_safe_clip_bottom(&spans, px(64.), below), Some(px(60.)));
2444
2445        // One taller than a line is: whatever crosses the edge keeps the part
2446        // that fits rather than leaving the box half empty.
2447        let one_block = [LineSpan {
2448            top: px(0.),
2449            bottom: px(60.),
2450            line_height: px(20.),
2451        }];
2452        assert_eq!(line_safe_clip_bottom(&one_block, px(200.), below), None);
2453
2454        // Nothing crosses the edge at all: the space under the last line is
2455        // the box's own, not a scrap of something below.
2456        assert_eq!(line_safe_clip_bottom(&spans, px(130.), px(128.)), None);
2457    }
2458
2459    #[test]
2460    fn a_line_taller_than_the_budget_keeps_the_part_that_fits() {
2461        use super::line_safe_clip_bottom;
2462        use crate::text::state::LineSpan;
2463
2464        // A heading line of 28px, in a box capped at one 26px body line.
2465        let heading = [LineSpan {
2466            top: px(70.),
2467            bottom: px(98.),
2468            line_height: px(28.),
2469        }];
2470
2471        assert_eq!(line_safe_clip_bottom(&heading, px(96.), px(400.)), None);
2472    }
2473
2474    #[test]
2475    fn the_clip_does_not_stop_on_a_row_of_border_and_padding() {
2476        use super::line_safe_clip_bottom;
2477        use crate::text::state::LineSpan;
2478
2479        // Two table rows, each one line of text, 9px of border and padding
2480        // between them.
2481        let rows = [
2482            LineSpan {
2483                top: px(100.),
2484                bottom: px(126.),
2485                line_height: px(26.),
2486            },
2487            LineSpan {
2488                top: px(135.),
2489                bottom: px(161.),
2490                line_height: px(26.),
2491            },
2492        ];
2493
2494        // Leaving out the second row's text would strand the 9px it leads
2495        // with, so the clip goes back to the row above it.
2496        assert_eq!(
2497            line_safe_clip_bottom(&rows, px(148.), px(400.)),
2498            Some(px(126.))
2499        );
2500    }
2501
2502    /// A clamped view nested the way an application nests one: inside a card,
2503    /// inside a region that fills a window of a known height. The height an
2504    /// ancestor hands down must not reach the clamped content and hide the
2505    /// overflow the clamp measures — with the content stretched to the capped
2506    /// box, nothing looks clipped and lines get cut in half.
2507    struct ClampedPageRoot {
2508        text_view: Entity<TextViewState>,
2509        max_lines: usize,
2510    }
2511
2512    impl Render for ClampedPageRoot {
2513        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2514            use crate::{h_flex, v_flex};
2515
2516            v_flex()
2517                .size_full()
2518                .p_4()
2519                .gap_4()
2520                .child(h_flex().max_w(px(480.)).gap_3().child("header"))
2521                .child(
2522                    v_flex()
2523                        .flex_1()
2524                        .min_h_0()
2525                        .gap_4()
2526                        .id("clamped-page-scroll")
2527                        .child(
2528                            v_flex()
2529                                .max_w(px(480.))
2530                                .p_3()
2531                                .gap_2()
2532                                .child(TextView::new(&self.text_view).max_lines(self.max_lines)),
2533                        )
2534                        .overflow_y_scroll(),
2535                )
2536        }
2537    }
2538
2539    #[wgpui::test]
2540    fn max_lines_measures_overflow_inside_a_sized_page(cx: &mut TestAppContext) {
2541        cx.update(crate::init);
2542        let (root, cx) = cx.add_window_view(|_, cx| {
2543            let text_view = cx.new(|cx| {
2544                TextViewState::markdown(
2545                    "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth\n\nseventh",
2546                    cx,
2547                )
2548            });
2549            ClampedPageRoot {
2550                text_view,
2551                max_lines: 3,
2552            }
2553        });
2554        let cx: &mut VisualTestContext = cx;
2555
2556        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
2557    }
2558
2559    #[wgpui::test]
2560    fn max_lines_clamps_overflowing_content(cx: &mut TestAppContext) {
2561        cx.update(crate::init);
2562        let (root, cx) = cx.add_window_view(|_, cx| {
2563            MaxLinesTestRoot::new(
2564                "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth",
2565                2,
2566                cx,
2567            )
2568        });
2569        let cx: &mut VisualTestContext = cx;
2570
2571        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
2572    }
2573
2574    #[wgpui::test]
2575    fn max_lines_leaves_short_content_unclamped(cx: &mut TestAppContext) {
2576        cx.update(crate::init);
2577        let (root, cx) = cx.add_window_view(|_, cx| MaxLinesTestRoot::new("only line", 3, cx));
2578        let cx: &mut VisualTestContext = cx;
2579
2580        assert!(!root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
2581    }
2582
2583    #[wgpui::test]
2584    fn heading_refinement_changes_rendered_heading_geometry(cx: &mut TestAppContext) {
2585        struct HeadingStyleRoot;
2586
2587        impl Render for HeadingStyleRoot {
2588            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2589                div()
2590                    .flex()
2591                    .items_start()
2592                    .child(
2593                        div()
2594                            .debug_selector(|| "default-h1".into())
2595                            .child(TextView::markdown("default-h1-view", "# Heading")),
2596                    )
2597                    .child(div().debug_selector(|| "custom-h1".into()).child(
2598                        TextView::markdown("custom-heading-view", "# Heading").style(
2599                            TextViewStyle::default().with_heading(|level| {
2600                                if level == 1 {
2601                                    StyleRefinement::default().pb(rems(2.))
2602                                } else {
2603                                    StyleRefinement::default()
2604                                }
2605                            }),
2606                        ),
2607                    ))
2608                    .child(
2609                        div()
2610                            .debug_selector(|| "default-h2".into())
2611                            .child(TextView::markdown("default-h2-view", "## Heading")),
2612                    )
2613                    .child(div().debug_selector(|| "custom-h2".into()).child(
2614                        TextView::markdown("custom-h2-view", "## Heading").style(
2615                            TextViewStyle::default().with_heading(|level| {
2616                                if level == 1 {
2617                                    StyleRefinement::default().pb(rems(2.))
2618                                } else {
2619                                    StyleRefinement::default()
2620                                }
2621                            }),
2622                        ),
2623                    ))
2624            }
2625        }
2626
2627        cx.update(crate::init);
2628        let (_, cx) = cx.add_window_view(|_, _| HeadingStyleRoot);
2629        cx.update(|window, cx| window.draw(cx).clear());
2630
2631        let default_h1 = cx.debug_bounds("default-h1").unwrap();
2632        let custom_h1 = cx.debug_bounds("custom-h1").unwrap();
2633        let default_h2 = cx.debug_bounds("default-h2").unwrap();
2634        let custom_h2 = cx.debug_bounds("custom-h2").unwrap();
2635        assert!(custom_h1.size.height > default_h1.size.height);
2636        assert_eq!(custom_h2.size.height, default_h2.size.height);
2637    }
2638
2639    #[wgpui::test]
2640    fn max_lines_disables_links_hidden_by_the_clamp(cx: &mut TestAppContext) {
2641        cx.update(crate::init);
2642        let (_, cx) = cx.add_window_view(|_, cx| {
2643            MaxLinesTestRoot::new(
2644                "first\n\nsecond\n\nthird\n\n[hidden](https://example.com)",
2645                2,
2646                cx,
2647            )
2648        });
2649        let cx: &mut VisualTestContext = cx;
2650
2651        // Click far below the clamped box, where the link would sit unclamped.
2652        cx.simulate_click(point(px(10.), px(150.)), Modifiers::default());
2653
2654        assert_eq!(cx.opened_url(), None);
2655    }
2656
2657    #[wgpui::test]
2658    fn scaled_inline_code_keeps_links_and_drag_selection(cx: &mut TestAppContext) {
2659        struct SelectionRoot {
2660            text_view: Entity<TextViewState>,
2661            format: crate::text::SelectionFormat,
2662        }
2663        impl Render for SelectionRoot {
2664            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2665                div()
2666                    .w(px(160.))
2667                    .child(crate::TextSelectionLayer)
2668                    .child(TextView::new(&self.text_view).selection_format(self.format))
2669            }
2670        }
2671        cx.update(crate::init);
2672        let (view, cx) = cx.add_window_view(|_, cx| SelectionRoot {
2673            format: crate::text::SelectionFormat::Plain,
2674            text_view: cx
2675                .new(|cx| TextViewState::markdown("[`code`](https://example.com) after", cx)),
2676        });
2677        let cx: &mut VisualTestContext = cx;
2678        cx.run_until_parked();
2679        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
2680        assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
2681        // Just past the code span's leading padding, on its first glyph.
2682        cx.simulate_mouse_down(
2683            point(px(5.), px(8.)),
2684            MouseButton::Left,
2685            Modifiers::default(),
2686        );
2687        cx.update(|window, cx| {
2688            let _ = window.draw(cx);
2689        });
2690        cx.simulate_mouse_move(
2691            point(px(155.), px(20.)),
2692            Some(MouseButton::Left),
2693            Modifiers::default(),
2694        );
2695        cx.update(|window, cx| {
2696            let _ = window.draw(cx);
2697        });
2698        cx.simulate_mouse_up(
2699            point(px(155.), px(20.)),
2700            MouseButton::Left,
2701            Modifiers::default(),
2702        );
2703        cx.update(|window, cx| {
2704            let _ = window.draw(cx);
2705        });
2706        let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
2707        assert_eq!(selected.trim(), "code after");
2708        view.update(cx, |view, cx| {
2709            view.format = crate::text::SelectionFormat::Source;
2710            cx.notify();
2711        });
2712        cx.update(|window, cx| {
2713            let _ = window.draw(cx);
2714        });
2715        let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
2716        assert_eq!(selected.trim(), "[`code`](https://example.com) after");
2717    }
2718
2719    /// Inline-code Markdown takes the deferred `InlineFlow` path. Its layout
2720    /// must use the heading's resolved typography rather than the ambient body
2721    /// style that remains after the heading's style stack has been popped.
2722    ///
2723    /// This is a real request-layout → measured-layout → prepaint → paint test:
2724    /// the deterministic text system makes bold glyphs wider than body glyphs.
2725    /// Before the fix, the code heading was allocated using normal body metrics
2726    /// but its fragments painted bold, so the wrapped heading text crossed into
2727    /// the following paragraph.
2728    #[test]
2729    fn inline_code_heading_reserves_painted_wrapped_lines_and_list_baseline() {
2730        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
2731        use wgpui::{TestApp, rems};
2732
2733        const MARKDOWN: &str = "The same words with inline code.\n\nThe same words with `inline code`.\n\n- The same words with inline code.\n- The same words with `inline code`.\n\n# Heading with inline code\n# Heading with `inline code`\n\nthis is a test";
2734
2735        struct MarkdownRoot {
2736            text_view: Entity<TextViewState>,
2737            width: Pixels,
2738            preview_zoom: f32,
2739        }
2740
2741        impl Render for MarkdownRoot {
2742            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2743                div()
2744                    .w(self.width)
2745                    // Match example-markdown: preview zoom changes TextView's
2746                    // inherited text size, not the window rem size.
2747                    .text_size(rems(self.preview_zoom))
2748                    .child(crate::TextSelectionLayer)
2749                    .child(TextView::new(&self.text_view).selectable(true))
2750            }
2751        }
2752
2753        fn draw(
2754            app: &mut TestApp,
2755            width: Pixels,
2756            preview_zoom: f32,
2757        ) -> (Bounds<Pixels>, Vec<Bounds<Pixels>>, String) {
2758            let mut window = app.open_window(|_, cx| MarkdownRoot {
2759                text_view: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
2760                width,
2761                preview_zoom,
2762            });
2763            window.draw();
2764            app.run_until_parked();
2765            window.draw();
2766            window.update(|root, _, cx| {
2767                root.text_view.update(cx, |state, cx| state.select_all(cx));
2768            });
2769            window.draw();
2770            window.read(|root, cx| {
2771                let state = root.text_view.read(cx);
2772                (
2773                    state.bounds(),
2774                    state.selection_adapter.text_bounds(),
2775                    state.selected_text(),
2776                )
2777            })
2778        }
2779
2780        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
2781        app.update(|cx| {
2782            crate::init(cx);
2783            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
2784        });
2785
2786        for (case, width, preview_zoom) in [
2787            // At the root 16px size the plain heading fits, while bold inline
2788            // fragments need their own measured widths.
2789            ("default-16px", px(600.), 1.),
2790            // A narrow view exercises intentional heading wrapping.
2791            ("narrow-16px", px(320.), 1.),
2792            // Preview zoom applies through `.text_size(rems(zoom))`.
2793            ("zoom-1.25", px(600.), 1.25),
2794        ] {
2795            let (view_bounds, text_bounds, selected_text) = draw(&mut app, width, preview_zoom);
2796            assert!(
2797                text_bounds.len() > 8,
2798                "{case}: expected all markdown fragments"
2799            );
2800            assert_eq!(
2801                selected_text.trim(),
2802                "The same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nHeading with inline code\nHeading with inline code\nthis is a test",
2803                "{case}: wrapped inline-code text was lost or duplicated"
2804            );
2805            let following = text_bounds.last().expect("following paragraph must paint");
2806            let painted_bottom = text_bounds
2807                .iter()
2808                .map(|bounds| bounds.bottom())
2809                .max()
2810                .expect("markdown must paint text");
2811            // This is intentionally not a fragment-count or selection-only
2812            // assertion: `text_bounds` are the shaped Inline layouts produced
2813            // during paint. No painted wrapped line may reach the following
2814            // paragraph's origin, and the TextView allocation must contain the
2815            // complete painted document.
2816            assert!(
2817                text_bounds[..text_bounds.len() - 1]
2818                    .iter()
2819                    .all(|bounds| bounds.bottom() <= following.top()),
2820                "{case}: heading/list text painted through the following paragraph;                  following={following:?}, text_bounds={text_bounds:?}, view={view_bounds:?}"
2821            );
2822            assert!(
2823                painted_bottom <= view_bounds.bottom(),
2824                "{case}: TextView height did not reserve its painted text;                  painted_bottom={painted_bottom:?}, view={view_bounds:?}"
2825            );
2826        }
2827    }
2828
2829    #[test]
2830    fn ordered_markdown_list_start_reaches_layout_marker() {
2831        use crate::text::inline::test_fonts::{WideMonoTextSystem, record_shaped_lines};
2832        use wgpui::TestApp;
2833
2834        struct MarkdownRoot {
2835            text_view: Entity<TextViewState>,
2836        }
2837
2838        impl Render for MarkdownRoot {
2839            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2840                div().w(px(400.)).child(TextView::new(&self.text_view))
2841            }
2842        }
2843
2844        #[derive(Clone, Copy)]
2845        enum Format {
2846            Markdown,
2847            Html,
2848        }
2849
2850        fn shaped_markers(format: Format, source: &str) -> Vec<String> {
2851            let (_, shaped_lines) = record_shaped_lines(|| {
2852                let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
2853                app.update(crate::init);
2854                let mut window = app.open_window(|_, cx| MarkdownRoot {
2855                    text_view: cx.new(|cx| match format {
2856                        Format::Markdown => TextViewState::markdown(source, cx),
2857                        Format::Html => TextViewState::html(source, cx),
2858                    }),
2859                });
2860                window.draw();
2861                app.run_until_parked();
2862                window.draw();
2863            });
2864
2865            let mut markers = shaped_lines
2866                .into_iter()
2867                .filter(|line| line.len() <= 3 && line.ends_with('.'))
2868                .collect::<Vec<_>>();
2869            markers.dedup();
2870            markers
2871        }
2872
2873        let starts_at_one = "1. one\n2. two";
2874        assert_eq!(
2875            shaped_markers(Format::Markdown, starts_at_one),
2876            ["1.", "2."]
2877        );
2878        assert_eq!(
2879            shaped_markers(Format::Html, "<ol><li>one</li><li>two</li></ol>"),
2880            ["1.", "2."]
2881        );
2882
2883        assert_eq!(
2884            shaped_markers(Format::Markdown, "3. hello\n4. world"),
2885            ["3.", "4."]
2886        );
2887
2888        let nested_starts_at_four = "1. outer\n\n   4. nested\n   5. again";
2889        assert_eq!(
2890            shaped_markers(Format::Markdown, nested_starts_at_four),
2891            ["1.", "D.", "E."]
2892        );
2893
2894        let nested_starts_at_zero = "1. outer\n\n   0. zero";
2895        assert_eq!(
2896            shaped_markers(Format::Markdown, nested_starts_at_zero),
2897            ["1.", "0."]
2898        );
2899    }
2900
2901    /// A line with inline code takes `InlineFlow` and a plain line takes the
2902    /// ordinary text path; both must be the same height, or a list with one
2903    /// code item is unevenly spaced (#3162). The fractional scale factor and
2904    /// zooms give line heights that are not whole logical pixels. Reusing the
2905    /// same window also checks the retained layouts after metric changes.
2906    #[test]
2907    fn inline_code_line_is_as_tall_as_a_plain_line() {
2908        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
2909        use wgpui::{TestApp, rems};
2910
2911        struct LineRoot {
2912            plain: Entity<TextViewState>,
2913            code: Entity<TextViewState>,
2914            preview_zoom: f32,
2915        }
2916
2917        impl Render for LineRoot {
2918            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2919                div()
2920                    .w(px(600.))
2921                    .text_size(rems(self.preview_zoom))
2922                    .child(TextView::new(&self.plain))
2923                    .child(TextView::new(&self.code))
2924            }
2925        }
2926
2927        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
2928        app.update(|cx| {
2929            crate::init(cx);
2930            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
2931        });
2932        for preview_zoom in [1., 1.25] {
2933            let mut window = app.open_window(|_, cx| LineRoot {
2934                plain: cx.new(|cx| TextViewState::markdown("plain body words", cx)),
2935                code: cx.new(|cx| TextViewState::markdown("plain `code` words", cx)),
2936                preview_zoom,
2937            });
2938            for rem_size in [px(16.), px(20.), px(16.)] {
2939                window.update(|_, window, cx| {
2940                    window.set_rem_size(rem_size);
2941                    cx.notify();
2942                });
2943                for scale_factor in [1.6, 2., 1.6] {
2944                    window.simulate_scale_factor_change(scale_factor);
2945                    window.draw();
2946                    app.run_until_parked();
2947                    window.draw();
2948                    let (plain, code) = window.read(|root, cx| {
2949                        (
2950                            root.plain.read(cx).bounds().size.height,
2951                            root.code.read(cx).bounds().size.height,
2952                        )
2953                    });
2954                    let expected = window.update(|root, window, _| {
2955                        let font_size = rems(root.preview_zoom).to_pixels(window.rem_size());
2956                        window.pixel_snap(
2957                            window
2958                                .text_style()
2959                                .line_height
2960                                .to_pixels(font_size.into(), window.rem_size()),
2961                        )
2962                    });
2963                    let context =
2964                        format!("scale {scale_factor}, rem {rem_size}, zoom {preview_zoom}");
2965                    assert_eq!(code, plain, "{context}");
2966                    assert_eq!(plain, expected, "stale plain-line metrics: {context}");
2967                }
2968            }
2969        }
2970    }
2971
2972    /// The code-bearing list item takes `InlineFlow`; the plain item takes the
2973    /// ordinary text path. Their first body glyphs must begin at the same row
2974    /// position relative to their own TextView origins.
2975    #[test]
2976    fn inline_code_list_body_paint_origin_matches_plain_list_item() {
2977        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
2978        use wgpui::{TestApp, rems};
2979
2980        struct ListRoot {
2981            plain: Entity<TextViewState>,
2982            code: Entity<TextViewState>,
2983            preview_zoom: f32,
2984        }
2985
2986        impl Render for ListRoot {
2987            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2988                div()
2989                    .w(px(600.))
2990                    .text_size(rems(self.preview_zoom))
2991                    .child(crate::TextSelectionLayer)
2992                    .child(TextView::new(&self.plain).selectable(true))
2993                    .child(TextView::new(&self.code).selectable(true))
2994            }
2995        }
2996
2997        fn draw(app: &mut TestApp, preview_zoom: f32) -> (Pixels, Pixels) {
2998            let mut window = app.open_window(|_, cx| ListRoot {
2999                plain: cx.new(|cx| TextViewState::markdown("- plain body words", cx)),
3000                code: cx.new(|cx| TextViewState::markdown("- plain `code` words", cx)),
3001                preview_zoom,
3002            });
3003            window.draw();
3004            app.run_until_parked();
3005            window.draw();
3006            window.read(|root, cx| {
3007                let first_body_line_top = |view: &Entity<TextViewState>| {
3008                    let view = view.read(cx);
3009                    let painted_line = view
3010                        .selection_adapter
3011                        .text_bounds()
3012                        .into_iter()
3013                        .next()
3014                        .expect("list item should paint its first body line");
3015                    painted_line.top() - view.bounds().top()
3016                };
3017                (
3018                    first_body_line_top(&root.plain),
3019                    first_body_line_top(&root.code),
3020                )
3021            })
3022        }
3023
3024        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3025        app.update(|cx| {
3026            crate::init(cx);
3027            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3028        });
3029        for (case, preview_zoom) in [("16px", 1.), ("zoom-1.25", 1.25), ("zoom-1.5", 1.5)] {
3030            let (plain_origin, code_origin) = draw(&mut app, preview_zoom);
3031            assert_eq!(
3032                code_origin, plain_origin,
3033                "{case}: code list body paint origin {code_origin:?} must match plain {plain_origin:?}"
3034            );
3035        }
3036    }
3037
3038    #[test]
3039    fn inline_code_fragment_does_not_paint_past_its_reserved_row() {
3040        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3041        use wgpui::TestApp;
3042
3043        const TEXT_BACKGROUND: u32 = 0x20f0b0;
3044
3045        struct MarkdownRoot {
3046            text_view: Entity<TextViewState>,
3047        }
3048
3049        impl Render for MarkdownRoot {
3050            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3051                div()
3052                    .w(px(640.))
3053                    .text_size(px(17.9))
3054                    .text_bg(wgpui::rgb(TEXT_BACKGROUND))
3055                    .child(TextView::new(&self.text_view))
3056            }
3057        }
3058
3059        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3060        app.update(|cx| {
3061            crate::init(cx);
3062            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3063        });
3064        let mut window = app.open_window(|_, cx| MarkdownRoot {
3065            text_view: cx.new(|cx| TextViewState::markdown("`main` starts the paragraph", cx)),
3066        });
3067        window.draw();
3068        app.run_until_parked();
3069        window.draw();
3070
3071        let (view_bounds, painted) = window.update(|root, window, cx| {
3072            let view_bounds = root
3073                .text_view
3074                .read(cx)
3075                .bounds()
3076                .scale(window.scale_factor());
3077            let text_background: wgpui::Background = wgpui::rgb(TEXT_BACKGROUND).into();
3078            let painted = window
3079                .painted_quads()
3080                .into_iter()
3081                .filter(|quad| quad.background == text_background)
3082                .map(|quad| quad.bounds)
3083                .collect::<Vec<_>>();
3084            (view_bounds, painted)
3085        });
3086
3087        assert!(
3088            !painted.is_empty(),
3089            "the inherited text background must make actual text paint observable"
3090        );
3091        assert!(
3092            painted
3093                .iter()
3094                .all(|bounds| bounds.bottom() <= view_bounds.bottom()),
3095            "an inline-code fragment wrapped a second time after InlineFlow reserved one row; \
3096             text background quads={painted:?}, reserved TextView bounds={view_bounds:?}"
3097        );
3098    }
3099
3100    #[test]
3101    fn table_row_backgrounds_follow_the_frame_corner_radius() {
3102        use wgpui::TestApp;
3103
3104        const HEAD_BACKGROUND: u32 = 0x11aa77;
3105        const RADIUS: f32 = 8.;
3106
3107        struct RoundedTableRoot {
3108            text_view: Entity<TextViewState>,
3109            scroll: bool,
3110        }
3111
3112        impl Render for RoundedTableRoot {
3113            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3114                let mut table = StyleRefinement::default();
3115                table.corner_radii.top_left = Some(px(RADIUS).into());
3116                table.corner_radii.top_right = Some(px(RADIUS).into());
3117                table.corner_radii.bottom_left = Some(px(RADIUS).into());
3118                table.corner_radii.bottom_right = Some(px(RADIUS).into());
3119                if self.scroll {
3120                    table.overflow.x = Some(wgpui::Overflow::Scroll);
3121                }
3122                let style = TextViewStyle::default()
3123                    .with_code_background(wgpui::rgb(HEAD_BACKGROUND).into())
3124                    .with_table(table);
3125                div()
3126                    .w(px(400.))
3127                    .child(TextView::new(&self.text_view).style(style))
3128            }
3129        }
3130
3131        for scroll in [false, true] {
3132            let mode = if scroll { "scroll" } else { "wrap" };
3133            let mut app = TestApp::new();
3134            app.update(crate::init);
3135            let mut window = app.open_window(|_, cx| RoundedTableRoot {
3136                text_view: cx
3137                    .new(|cx| TextViewState::markdown("| a | b |\n| --- | --- |\n| 1 | 2 |", cx)),
3138                scroll,
3139            });
3140            window.draw();
3141            app.run_until_parked();
3142            window.draw();
3143
3144            let (quad, scale) = window.update(|_, window, _| {
3145                let head: wgpui::Background = wgpui::rgb(HEAD_BACKGROUND).into();
3146                let quad = window
3147                    .painted_quads()
3148                    .into_iter()
3149                    .find(|quad| quad.background == head)
3150                    .unwrap_or_else(|| panic!("{mode}: the header background quad is painted"));
3151                (quad, window.scale_factor())
3152            });
3153
3154            // GPUI clips children with a rectangular mask, so the header fill
3155            // must carry the frame radius itself, inset by the 1px border.
3156            let expected = px(RADIUS - 1.).scale(scale);
3157            assert_eq!(quad.corner_radii.top_left, expected, "{mode}: top left");
3158            assert_eq!(quad.corner_radii.top_right, expected, "{mode}: top right");
3159            let square = px(0.).scale(scale);
3160            assert_eq!(quad.corner_radii.bottom_left, square, "{mode}: bottom left");
3161            assert_eq!(
3162                quad.corner_radii.bottom_right, square,
3163                "{mode}: bottom right"
3164            );
3165        }
3166    }
3167
3168    /// A table wider than its frame shrinks its widest column. A narrower
3169    /// column keeps its content width rather than shrinking by the same
3170    /// ratio and wrapping the end of its text onto a line of its own, in the
3171    /// header and the body alike, and with the cell and frame refinements
3172    /// the text renders with.
3173    #[test]
3174    fn table_keeps_narrow_columns_on_one_line_while_wide_ones_wrap() {
3175        use crate::text::inline::test_fonts::WideMonoTextSystem;
3176        use std::sync::Arc;
3177        use wgpui::TestApp;
3178
3179        const CELL_BACKGROUND: u32 = 0x11aa77;
3180
3181        struct TableRoot {
3182            text_view: Entity<TextViewState>,
3183            width: Pixels,
3184            style: TextViewStyle,
3185        }
3186
3187        impl Render for TableRoot {
3188            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3189                div()
3190                    .w(self.width)
3191                    .child(TextView::new(&self.text_view).style(self.style.clone()))
3192            }
3193        }
3194
3195        let short = "Operating revenue (USD)";
3196        let source = format!(
3197            "| {short} | Note |\n| --- | --- |\n| {short} | x |\n| 1 | {} |",
3198            "word ".repeat(30)
3199        );
3200        // Heights of the first column's cells, top to bottom.
3201        let first_column = |width: f32, style: TextViewStyle| {
3202            let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3203            app.update(crate::init);
3204            let cell = style.table_cell().clone().bg(wgpui::rgb(CELL_BACKGROUND));
3205            let style = style.with_table_cell(cell);
3206            let mut window = app.open_window(|_, cx| TableRoot {
3207                text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
3208                width: px(width),
3209                style,
3210            });
3211            window.draw();
3212            app.run_until_parked();
3213            window.draw();
3214            window.update(|_, window, _| {
3215                let background: wgpui::Background = wgpui::rgb(CELL_BACKGROUND).into();
3216                let cells: Vec<_> = window
3217                    .painted_quads()
3218                    .into_iter()
3219                    .filter(|quad| quad.background == background)
3220                    .map(|quad| quad.bounds)
3221                    .collect();
3222                let left = cells.iter().map(|bounds| bounds.origin.x).min().unwrap();
3223                let mut column: Vec<_> = cells
3224                    .into_iter()
3225                    .filter(|bounds| bounds.origin.x == left)
3226                    .collect();
3227                column.sort_by_key(|bounds| bounds.origin.y);
3228                column
3229                    .iter()
3230                    .map(|bounds| bounds.size.height)
3231                    .collect::<Vec<_>>()
3232            })
3233        };
3234        let scroll = || {
3235            let mut table = StyleRefinement::default();
3236            table.overflow.x = Some(wgpui::Overflow::Scroll);
3237            TextViewStyle::default().with_table(table)
3238        };
3239
3240        for (layout, style) in [("wrap", TextViewStyle::default()), ("scroll", scroll())] {
3241            let fits = first_column(4000., style.clone());
3242            let narrow = first_column(700., style);
3243            assert_eq!(fits.len(), 3, "{layout}: three rows");
3244            assert_eq!(fits[0], fits[2], "{layout}: the header fits on one line");
3245            assert_eq!(narrow[..2], fits[..2], "{layout}: the short column wraps");
3246        }
3247
3248        let single_line = first_column(4000., TextViewStyle::default())[0];
3249        let padded = TextViewStyle::default().with_table_cell(StyleRefinement::default().px_4());
3250        assert_eq!(
3251            first_column(4000., padded)[0],
3252            single_line,
3253            "the cell padding refinement leaves the text its measured width"
3254        );
3255        let bold = TextViewStyle::default()
3256            .with_table(StyleRefinement::default().font_weight(wgpui::FontWeight::BOLD));
3257        assert_eq!(
3258            first_column(4000., bold)[0],
3259            single_line,
3260            "the table text refinement is measured"
3261        );
3262    }
3263
3264    #[wgpui::test]
3265    fn markdown_link_opens_url_without_handler(cx: &mut TestAppContext) {
3266        cx.update(crate::init);
3267        let (_, cx) =
3268            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
3269        let cx: &mut VisualTestContext = cx;
3270
3271        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
3272
3273        assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
3274    }
3275
3276    #[wgpui::test]
3277    fn right_click_does_not_open_url_without_handler(cx: &mut TestAppContext) {
3278        cx.update(crate::init);
3279        let (_, cx) =
3280            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
3281        let cx: &mut VisualTestContext = cx;
3282
3283        cx.simulate_mouse_down(
3284            point(px(10.), px(10.)),
3285            MouseButton::Right,
3286            Modifiers::default(),
3287        );
3288        cx.simulate_mouse_up(
3289            point(px(10.), px(10.)),
3290            MouseButton::Right,
3291            Modifiers::default(),
3292        );
3293
3294        assert_eq!(cx.opened_url(), None);
3295    }
3296
3297    #[wgpui::test]
3298    fn link_handler_receives_button_and_modifiers(cx: &mut TestAppContext) {
3299        use std::sync::{Arc, Mutex};
3300
3301        struct LinkRoot {
3302            text_view: Entity<TextViewState>,
3303            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
3304        }
3305
3306        impl Render for LinkRoot {
3307            fn render(
3308                &mut self,
3309                _window: &mut Window,
3310                _cx: &mut Context<Self>,
3311            ) -> impl IntoElement {
3312                let clicks = self.clicks.clone();
3313                div()
3314                    .w(px(240.))
3315                    .child(
3316                        TextView::new(&self.text_view).on_link_click(move |url, event, _, _| {
3317                            clicks.lock().unwrap().push((url.clone(), event.clone()));
3318                        }),
3319                    )
3320            }
3321        }
3322
3323        cx.update(crate::init);
3324        let clicks = Arc::new(Mutex::new(Vec::new()));
3325        let captured = clicks.clone();
3326        let (_, cx) = cx.add_window_view(move |_, cx| LinkRoot {
3327            text_view: cx.new(|cx| TextViewState::markdown("[example](https://example.com)", cx)),
3328            clicks,
3329        });
3330        let cx: &mut VisualTestContext = cx;
3331
3332        let mut modifiers = Modifiers::default();
3333        modifiers.control = true;
3334        cx.simulate_click(point(px(10.), px(10.)), modifiers);
3335        cx.simulate_mouse_down(
3336            point(px(10.), px(10.)),
3337            MouseButton::Middle,
3338            Modifiers::default(),
3339        );
3340        cx.simulate_mouse_up(
3341            point(px(10.), px(10.)),
3342            MouseButton::Middle,
3343            Modifiers::default(),
3344        );
3345        cx.simulate_mouse_down(
3346            point(px(10.), px(10.)),
3347            MouseButton::Right,
3348            Modifiers::default(),
3349        );
3350        cx.simulate_mouse_up(
3351            point(px(10.), px(10.)),
3352            MouseButton::Right,
3353            Modifiers::default(),
3354        );
3355
3356        let clicks = captured.lock().unwrap();
3357        assert_eq!(clicks.len(), 3);
3358        assert_eq!(clicks[0].0, "https://example.com");
3359        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
3360        assert!(clicks[0].1.modifiers().control);
3361        assert!(clicks[1].1.is_middle_click());
3362        assert!(clicks[2].1.is_right_click());
3363        assert_eq!(cx.opened_url(), None);
3364    }
3365
3366    #[wgpui::test]
3367    fn inline_object_inherits_bold_and_link_clicks_without_opening_on_drag(
3368        cx: &mut TestAppContext,
3369    ) {
3370        use std::sync::{Arc, Mutex};
3371        struct Root {
3372            state: Entity<TextViewState>,
3373            clicks: Arc<Mutex<Vec<SharedString>>>,
3374        }
3375        impl Render for Root {
3376            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3377                let clicks = self.clicks.clone();
3378                let extensions = crate::text::MarkdownExtensions::default().plugin(
3379                    crate::text::markdown_ext::TestInlinePlugin::new("math")
3380                        .parse_with(|node, _| {
3381                            matches!(node, markdown::mdast::Node::InlineMath(_)).then(|| {
3382                                super::super::MarkdownNode::new("math", ()).text("formula")
3383                            })
3384                        })
3385                        .render_with(|_, context, _, _| {
3386                            assert_eq!(context.text_style().font_weight, wgpui::FontWeight::BOLD);
3387                            Some(super::super::InlineElement::new(div().child("formula")))
3388                        }),
3389                );
3390                div().w(px(300.)).child(crate::TextSelectionLayer).child(
3391                    TextView::new(&self.state)
3392                        .markdown_extensions(extensions)
3393                        .on_link_click(move |url, _, _, _| {
3394                            clicks.lock().unwrap().push(url.clone())
3395                        }),
3396                )
3397            }
3398        }
3399        cx.update(crate::init);
3400        let clicks = Arc::new(Mutex::new(Vec::new()));
3401        let captured = clicks.clone();
3402        let (root, cx) = cx.add_window_view(move |_, cx| Root {
3403            state: cx.new(|cx| TextViewState::markdown("**[$x$](https://example.com)**", cx)),
3404            clicks,
3405        });
3406        let cx: &mut VisualTestContext = cx;
3407        cx.run_until_parked();
3408        cx.update(|window, cx| {
3409            let _ = window.draw(cx);
3410        });
3411        let bounds = root.read_with(cx, |root, cx| {
3412            root.state.read(cx).selection_adapter.text_bounds()[0]
3413        });
3414        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
3415            cx.simulate_mouse_down(bounds.center(), button, Modifiers::default());
3416            cx.simulate_mouse_up(bounds.center(), button, Modifiers::default());
3417        }
3418        assert_eq!(captured.lock().unwrap().len(), 3);
3419        let start = point(bounds.left() + px(1.), bounds.center().y);
3420        let end = point(bounds.right() - px(1.), bounds.center().y);
3421        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
3422        cx.update(|window, cx| {
3423            let _ = window.draw(cx);
3424        });
3425        cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
3426        cx.update(|window, cx| {
3427            let _ = window.draw(cx);
3428        });
3429        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
3430        assert_eq!(captured.lock().unwrap().len(), 3);
3431    }
3432
3433    #[wgpui::test]
3434    fn linked_image_handler_receives_left_middle_and_right_clicks(cx: &mut TestAppContext) {
3435        use std::sync::{Arc, Mutex};
3436
3437        struct LinkedImageRoot {
3438            text_view: Entity<TextViewState>,
3439            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
3440        }
3441
3442        impl Render for LinkedImageRoot {
3443            fn render(
3444                &mut self,
3445                _window: &mut Window,
3446                _cx: &mut Context<Self>,
3447            ) -> impl IntoElement {
3448                let clicks = self.clicks.clone();
3449                div().w(px(160.)).child(
3450                    TextView::new(&self.text_view)
3451                        .selectable(true)
3452                        .on_link_click(move |url, event, _, _| {
3453                            clicks.lock().unwrap().push((url.clone(), event.clone()));
3454                        }),
3455                )
3456            }
3457        }
3458
3459        cx.update(crate::init);
3460        let clicks = Arc::new(Mutex::new(Vec::new()));
3461        let captured = clicks.clone();
3462        let (content, cx) = cx.add_window_view(move |_, cx| LinkedImageRoot {
3463                text_view: cx.new(|cx| {
3464                    TextViewState::markdown(
3465                        r#"Before [<img src="https://example.com/image.svg" width="32" height="32">](https://example.com/image-link) after."#,
3466                        cx,
3467                    )
3468                }),
3469                clicks,
3470            }
3471        );
3472        let cx: &mut VisualTestContext = cx;
3473        cx.run_until_parked();
3474        cx.update(|window, cx| {
3475            let _ = window.draw(cx);
3476        });
3477
3478        let inline_bounds = content.read_with(cx, |content, cx| {
3479            content.text_view.read(cx).selection_adapter.text_bounds()
3480        });
3481        assert!(
3482            inline_bounds.len() >= 2,
3483            "linked image needs text bounds on both sides: {inline_bounds:?}"
3484        );
3485        assert!(
3486            inline_bounds[1].left() - inline_bounds[0].right() >= px(24.),
3487            "linked image did not reserve the expected click target: {inline_bounds:?}"
3488        );
3489        let position = point(
3490            inline_bounds[0].right() + (inline_bounds[1].left() - inline_bounds[0].right()) * 0.5,
3491            inline_bounds[0].top() + px(8.),
3492        );
3493        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
3494            cx.simulate_mouse_down(position, button, Modifiers::default());
3495            cx.simulate_mouse_up(position, button, Modifiers::default());
3496        }
3497
3498        let clicks = captured.lock().unwrap();
3499        assert_eq!(clicks.len(), 3);
3500        assert!(
3501            clicks
3502                .iter()
3503                .all(|(url, _)| url == "https://example.com/image-link")
3504        );
3505        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
3506        assert!(clicks[1].1.is_middle_click());
3507        assert!(clicks[2].1.is_right_click());
3508        assert_eq!(cx.opened_url(), None);
3509    }
3510
3511    #[wgpui::test]
3512    fn clipped_markdown_cannot_start_selection(cx: &mut TestAppContext) {
3513        cx.update(crate::init);
3514        let (view, cx) = cx
3515            .add_window_view(|_, cx| TextViewTestRoot::new("visible\n\nhidden selection text", cx));
3516        let cx: &mut VisualTestContext = cx;
3517
3518        cx.simulate_mouse_down(
3519            point(px(10.), px(34.)),
3520            MouseButton::Left,
3521            Modifiers::default(),
3522        );
3523        cx.simulate_mouse_move(
3524            point(px(90.), px(34.)),
3525            Some(MouseButton::Left),
3526            Modifiers::default(),
3527        );
3528        cx.simulate_mouse_up(
3529            point(px(90.), px(34.)),
3530            MouseButton::Left,
3531            Modifiers::default(),
3532        );
3533
3534        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
3535        assert!(
3536            selected_text.is_empty(),
3537            "unexpected selection: {selected_text:?}"
3538        );
3539    }
3540
3541    /// A tall selectable TextView clipped by a short `overflow_hidden` viewport,
3542    /// with a large blank footer below so a drag can extend the selection band
3543    /// past the bottom of the clip while still proxy-anchoring to the view.
3544    struct ClippedTallTextViewTestRoot {
3545        text_view: Entity<TextViewState>,
3546    }
3547
3548    impl ClippedTallTextViewTestRoot {
3549        fn new(cx: &mut Context<Self>) -> Self {
3550            // Four separate blocks; only the first (and maybe part of the
3551            // second) fit inside the 40px clip. "charlie"/"delta" render well
3552            // below it.
3553            let text_view =
3554                cx.new(|cx| TextViewState::markdown("alpha\n\nbravo\n\ncharlie\n\ndelta", cx));
3555            Self { text_view }
3556        }
3557    }
3558
3559    impl Render for ClippedTallTextViewTestRoot {
3560        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3561            div()
3562                .w(px(200.))
3563                .child(crate::TextSelectionLayer)
3564                .child(
3565                    div()
3566                        .h(px(40.))
3567                        .overflow_hidden()
3568                        .child(TextView::new(&self.text_view).selectable(true)),
3569                )
3570                // A tall blank footer so a drag can reach a y below the clipped
3571                // text; a press there proxy-anchors to the TextView above.
3572                .child(div().h(px(160.)))
3573        }
3574    }
3575
3576    /// Regression for copying a selection taller than the visible viewport.
3577    ///
3578    /// The selection band runs from visible text at the top down to a point
3579    /// far below the clip. Every glyph of the painted TextView is laid out even
3580    /// though the lower ones are clipped away, so the copied text must include
3581    /// the clipped-out "charlie"/"delta" — not just what is on screen. This
3582    /// guards against re-adding a `content_mask` gate in
3583    /// `Inline::layout_selections`.
3584    #[wgpui::test]
3585    fn selection_band_beyond_clip_copies_offscreen_text(cx: &mut TestAppContext) {
3586        cx.update(crate::init);
3587        let (content, cx) = cx.add_window_view(|_, cx| ClippedTallTextViewTestRoot::new(cx));
3588        let cx: &mut VisualTestContext = cx;
3589
3590        cx.run_until_parked();
3591        cx.update(|window, cx| {
3592            let _ = window.draw(cx);
3593        });
3594
3595        // Anchor on visible text near the top, then drag to a point well below
3596        // the 40px clip (into the blank footer) and to the far right so the
3597        // last line is fully covered.
3598        cx.simulate_mouse_down(
3599            point(px(2.), px(8.)),
3600            MouseButton::Left,
3601            Modifiers::default(),
3602        );
3603        cx.update(|window, cx| {
3604            let _ = window.draw(cx);
3605        });
3606        cx.simulate_mouse_move(
3607            point(px(180.), px(150.)),
3608            Some(MouseButton::Left),
3609            Modifiers::default(),
3610        );
3611        cx.update(|window, cx| {
3612            let _ = window.draw(cx);
3613        });
3614        cx.simulate_mouse_up(
3615            point(px(180.), px(150.)),
3616            MouseButton::Left,
3617            Modifiers::default(),
3618        );
3619        cx.update(|window, cx| {
3620            let _ = window.draw(cx);
3621        });
3622
3623        let selected_text =
3624            content.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
3625        assert!(
3626            selected_text.contains("delta"),
3627            "clipped-out text was not copied: {selected_text:?}"
3628        );
3629        assert!(
3630            selected_text.contains("charlie"),
3631            "clipped-out text was not copied: {selected_text:?}"
3632        );
3633    }
3634
3635    #[wgpui::test]
3636    fn double_click_selects_word(cx: &mut TestAppContext) {
3637        cx.update(crate::init);
3638        let (view, cx) =
3639            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
3640
3641        let cx: &mut VisualTestContext = cx;
3642        cx.run_until_parked();
3643        cx.update(|window, cx| {
3644            let _ = window.draw(cx);
3645        });
3646        let position = point(px(10.), px(16.));
3647        cx.simulate_event(MouseDownEvent {
3648            position,
3649            modifiers: Modifiers::default(),
3650            button: MouseButton::Left,
3651            click_count: 2,
3652            first_mouse: false,
3653        });
3654        cx.simulate_event(MouseUpEvent {
3655            position,
3656            modifiers: Modifiers::default(),
3657            button: MouseButton::Left,
3658            click_count: 2,
3659        });
3660        cx.update(|window, cx| {
3661            let _ = window.draw(cx);
3662        });
3663
3664        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
3665        assert_eq!(selected_text.trim(), "quick");
3666    }
3667
3668    #[wgpui::test]
3669    fn long_press_selects_word_then_drag_extends_selection(cx: &mut TestAppContext) {
3670        struct TouchRoot {
3671            text_view: Entity<TextViewState>,
3672        }
3673        impl Render for TouchRoot {
3674            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3675                div()
3676                    .w(px(300.))
3677                    .child(crate::TextSelectionLayer)
3678                    .child(TextView::new(&self.text_view).selectable(true))
3679            }
3680        }
3681        cx.update(crate::init);
3682        let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
3683            text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
3684        });
3685        cx.run_until_parked();
3686        cx.update(|window, cx| {
3687            let _ = window.draw(cx);
3688        });
3689        let start_position = point(px(10.), px(16.));
3690        cx.simulate_event(wgpui::LongPressEvent {
3691            phase: wgpui::TouchPhase::Started,
3692            start_position,
3693            position: start_position,
3694        });
3695        cx.update(|window, cx| {
3696            let _ = window.draw(cx);
3697        });
3698        assert_eq!(
3699            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
3700                .trim(),
3701            "quick"
3702        );
3703        for phase in [wgpui::TouchPhase::Moved, wgpui::TouchPhase::Ended] {
3704            cx.simulate_event(wgpui::LongPressEvent {
3705                phase,
3706                start_position,
3707                position: point(px(220.), px(16.)),
3708            });
3709        }
3710        cx.update(|window, cx| {
3711            let _ = window.draw(cx);
3712        });
3713        assert_eq!(
3714            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
3715                .trim(),
3716            "quick select value"
3717        );
3718    }
3719
3720    #[wgpui::test]
3721    fn long_press_release_keeps_handles_which_drag_the_selection(cx: &mut TestAppContext) {
3722        use crate::{SelectionEdge, TextSelection};
3723
3724        struct TouchRoot {
3725            text_view: Entity<TextViewState>,
3726        }
3727        impl Render for TouchRoot {
3728            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3729                div()
3730                    .w(px(300.))
3731                    .child(crate::TextSelectionLayer)
3732                    .child(TextView::new(&self.text_view).selectable(true))
3733            }
3734        }
3735        cx.update(crate::init);
3736        let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
3737            text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
3738        });
3739        let draw = |cx: &mut VisualTestContext| {
3740            cx.update(|window, cx| {
3741                let _ = window.draw(cx);
3742            });
3743        };
3744        let selected = |cx: &mut VisualTestContext| {
3745            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
3746                .trim()
3747                .to_string()
3748        };
3749        cx.run_until_parked();
3750        draw(cx);
3751
3752        let start_position = point(px(70.), px(16.));
3753        for phase in [wgpui::TouchPhase::Started, wgpui::TouchPhase::Ended] {
3754            cx.simulate_event(wgpui::LongPressEvent {
3755                phase,
3756                start_position,
3757                position: start_position,
3758            });
3759            draw(cx);
3760        }
3761        assert_eq!(selected(cx), "select");
3762        let snapshot = cx
3763            .update(|window, cx| TextSelection::touch_selection(window, cx))
3764            .expect("a released long press keeps its handles");
3765        assert!(snapshot.is_menu_open());
3766        assert!(!snapshot.is_empty());
3767        assert!(snapshot.start().left() < snapshot.end().left());
3768
3769        // Drag the end handle to the end of the line. The finger holds the
3770        // knob below the line, the selection follows along the line.
3771        let end = snapshot.end();
3772        let finger = point(end.left(), end.bottom() + px(20.));
3773        cx.update(|window, cx| {
3774            TextSelection::begin_edge_drag(SelectionEdge::End, finger, window, cx);
3775        });
3776        draw(cx);
3777        let snapshot = cx
3778            .update(|window, cx| TextSelection::touch_selection(window, cx))
3779            .unwrap();
3780        assert_eq!(snapshot.dragging(), Some(SelectionEdge::End));
3781        assert!(!snapshot.is_menu_open());
3782        cx.update(|window, cx| {
3783            TextSelection::update_edge_drag(point(px(290.), finger.y), window, cx);
3784        });
3785        draw(cx);
3786        assert_eq!(selected(cx), "select value");
3787        cx.update(|window, cx| TextSelection::end_edge_drag(window, cx));
3788        draw(cx);
3789        let snapshot = cx
3790            .update(|window, cx| TextSelection::touch_selection(window, cx))
3791            .unwrap();
3792        assert!(snapshot.is_menu_open());
3793        assert_eq!(snapshot.dragging(), None);
3794        let select_start = snapshot.start().left();
3795
3796        // Select All from the menu is a view-local selection; its handles
3797        // still drag, turning it back into a point selection.
3798        cx.update(|_, cx| {
3799            view.update(cx, |root, cx| {
3800                root.text_view.update(cx, |state, cx| state.select_all(cx));
3801            });
3802        });
3803        draw(cx);
3804        assert_eq!(selected(cx), "quick select value");
3805        let snapshot = cx
3806            .update(|window, cx| TextSelection::touch_selection(window, cx))
3807            .expect("select all keeps the touch selection");
3808        let start = snapshot.start();
3809        cx.update(|window, cx| {
3810            TextSelection::begin_edge_drag(SelectionEdge::Start, start.origin, window, cx);
3811            TextSelection::update_edge_drag(point(select_start, start.origin.y), window, cx);
3812            TextSelection::end_edge_drag(window, cx);
3813        });
3814        draw(cx);
3815        assert_eq!(selected(cx), "select value");
3816
3817        // A press on the menu leaves the selection alone; one on the text
3818        // clears it.
3819        let menu = wgpui::Bounds::new(point(px(0.), px(200.)), wgpui::size(px(120.), px(32.)));
3820        cx.update(|window, cx| TextSelection::register_touch_ui(menu, window, cx));
3821        cx.simulate_event(MouseDownEvent {
3822            position: point(px(10.), px(210.)),
3823            modifiers: Modifiers::default(),
3824            button: MouseButton::Left,
3825            click_count: 1,
3826            first_mouse: false,
3827        });
3828        assert_eq!(selected(cx), "select value");
3829        cx.simulate_event(MouseDownEvent {
3830            position: point(px(10.), px(16.)),
3831            modifiers: Modifiers::default(),
3832            button: MouseButton::Left,
3833            click_count: 1,
3834            first_mouse: false,
3835        });
3836        cx.simulate_event(MouseUpEvent {
3837            position: point(px(10.), px(16.)),
3838            modifiers: Modifiers::default(),
3839            button: MouseButton::Left,
3840            click_count: 1,
3841        });
3842        draw(cx);
3843        assert!(
3844            cx.update(|window, cx| TextSelection::touch_selection(window, cx))
3845                .is_none()
3846        );
3847    }
3848
3849    #[wgpui::test]
3850    fn triple_click_selects_paragraph(cx: &mut TestAppContext) {
3851        cx.update(crate::init);
3852        let (view, cx) =
3853            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
3854
3855        let cx: &mut VisualTestContext = cx;
3856        cx.run_until_parked();
3857        cx.update(|window, cx| {
3858            let _ = window.draw(cx);
3859        });
3860
3861        let position = point(px(10.), px(10.));
3862        cx.simulate_event(MouseDownEvent {
3863            position,
3864            modifiers: Modifiers::default(),
3865            button: MouseButton::Left,
3866            click_count: 3,
3867            first_mouse: false,
3868        });
3869        cx.simulate_event(MouseUpEvent {
3870            position,
3871            modifiers: Modifiers::default(),
3872            button: MouseButton::Left,
3873            click_count: 3,
3874        });
3875        cx.update(|window, cx| {
3876            let _ = window.draw(cx);
3877        });
3878
3879        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
3880        assert_eq!(selected_text.trim(), "quick select value");
3881    }
3882
3883    mod multi_click_drag {
3884        use super::*;
3885
3886        struct Root {
3887            text_view: Entity<TextViewState>,
3888        }
3889
3890        impl Render for Root {
3891            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3892                div()
3893                    .w(px(400.))
3894                    .child(crate::TextSelectionLayer)
3895                    .child(TextView::new(&self.text_view).selectable(true))
3896            }
3897        }
3898
3899        fn setup<'a>(
3900            markdown: &str,
3901            cx: &'a mut TestAppContext,
3902        ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
3903            cx.update(crate::init);
3904            let (root, cx) = cx.add_window_view(|_, cx| Root {
3905                text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3906            });
3907            cx.run_until_parked();
3908            cx.update(|window, cx| window.draw(cx).clear());
3909            (root.read_with(cx, |root, _| root.text_view.clone()), cx)
3910        }
3911
3912        /// Just inside the character at `index` of the painted `text`.
3913        fn position(
3914            state: &Entity<TextViewState>,
3915            text: &str,
3916            index: usize,
3917            cx: &mut VisualTestContext,
3918        ) -> wgpui::Point<Pixels> {
3919            state.read_with(cx, |state, _| {
3920                state.selection_adapter.text_position(text, index)
3921            })
3922        }
3923
3924        fn press(
3925            position: wgpui::Point<Pixels>,
3926            click_count: usize,
3927            shift: bool,
3928            cx: &mut VisualTestContext,
3929        ) {
3930            cx.simulate_event(MouseDownEvent {
3931                position,
3932                modifiers: Modifiers {
3933                    shift,
3934                    ..Default::default()
3935                },
3936                button: MouseButton::Left,
3937                click_count,
3938                first_mouse: false,
3939            });
3940        }
3941
3942        fn drag(position: wgpui::Point<Pixels>, cx: &mut VisualTestContext) {
3943            cx.simulate_event(wgpui::MouseMoveEvent {
3944                position,
3945                pressed_button: Some(MouseButton::Left),
3946                modifiers: Modifiers::default(),
3947            });
3948        }
3949
3950        fn release(position: wgpui::Point<Pixels>, click_count: usize, cx: &mut VisualTestContext) {
3951            cx.simulate_event(MouseUpEvent {
3952                position,
3953                modifiers: Modifiers::default(),
3954                button: MouseButton::Left,
3955                click_count,
3956            });
3957        }
3958
3959        fn selected(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> String {
3960            cx.update(|window, cx| window.draw(cx).clear());
3961            state.read_with(cx, |state, _| state.selected_text().trim().to_string())
3962        }
3963
3964        #[wgpui::test]
3965        fn double_click_drag_extends_the_selection_by_words(cx: &mut TestAppContext) {
3966            let (first, second) = ("alpha beta gamma", "delta epsilon zeta");
3967            let (state, cx) = setup(&format!("{first}\n\n{second}"), cx);
3968
3969            press(position(&state, first, 7, cx), 2, false, cx);
3970            assert_eq!(selected(&state, cx), "beta");
3971            drag(position(&state, first, 8, cx), cx);
3972            assert_eq!(selected(&state, cx), "beta");
3973            drag(position(&state, first, 13, cx), cx);
3974            assert_eq!(selected(&state, cx), "beta gamma");
3975            // Backward, the whole of the word the drag started from stays.
3976            drag(position(&state, first, 1, cx), cx);
3977            assert_eq!(selected(&state, cx), "alpha beta");
3978            let end = position(&state, second, 8, cx);
3979            drag(end, cx);
3980            assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
3981            release(end, 2, cx);
3982            assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
3983        }
3984
3985        #[wgpui::test]
3986        fn triple_click_drag_extends_the_selection_by_paragraphs(cx: &mut TestAppContext) {
3987            let (state, cx) = setup("first one\n\nsecond one\n\nthird one", cx);
3988
3989            press(position(&state, "second one", 2, cx), 3, false, cx);
3990            assert_eq!(selected(&state, cx), "second one");
3991            drag(position(&state, "third one", 2, cx), cx);
3992            assert_eq!(selected(&state, cx), "second one\nthird one");
3993            let end = position(&state, "first one", 2, cx);
3994            drag(end, cx);
3995            assert_eq!(selected(&state, cx), "first one\nsecond one");
3996            release(end, 3, cx);
3997            assert_eq!(selected(&state, cx), "first one\nsecond one");
3998        }
3999
4000        /// A hard break adds a line to a paragraph without ending that paragraph.
4001        #[wgpui::test]
4002        fn triple_click_drag_and_shift_click_keep_hard_break_paragraphs_whole(
4003            cx: &mut TestAppContext,
4004        ) {
4005            let first = "first top\nfirst bottom";
4006            let last = "last top\nlast bottom";
4007            let (state, cx) = setup(
4008                "first top  \nfirst bottom\n\nmiddle\n\nlast top  \nlast bottom",
4009                cx,
4010            );
4011
4012            press(position(&state, "middle", 2, cx), 3, false, cx);
4013            assert_eq!(selected(&state, cx), "middle");
4014            let after = position(&state, last, 2, cx);
4015            drag(after, cx);
4016            assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4017            let before = position(&state, first, "first top\n".len() + 2, cx);
4018            drag(before, cx);
4019            assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4020            release(before, 3, cx);
4021
4022            press(after, 1, true, cx);
4023            release(after, 1, cx);
4024            assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4025            press(before, 1, true, cx);
4026            release(before, 1, cx);
4027            assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4028        }
4029
4030        /// Inline code lays a paragraph out in pieces; the drag snaps the same.
4031        #[wgpui::test]
4032        fn multi_click_drag_snaps_across_inline_code(cx: &mut TestAppContext) {
4033            let (state, cx) = setup("plain words\n\nuse `code` in here", cx);
4034
4035            press(position(&state, "plain words", 8, cx), 2, false, cx);
4036            drag(position(&state, " in here", 6, cx), cx);
4037            assert_eq!(selected(&state, cx), "words\nuse code in here");
4038            release(position(&state, " in here", 6, cx), 2, cx);
4039
4040            press(position(&state, "plain words", 2, cx), 3, false, cx);
4041            assert_eq!(selected(&state, cx), "plain words");
4042            drag(position(&state, "use ", 1, cx), cx);
4043            assert_eq!(selected(&state, cx), "plain words\nuse code in here");
4044        }
4045
4046        #[wgpui::test]
4047        fn shift_click_after_a_double_click_extends_by_words(cx: &mut TestAppContext) {
4048            let text = "alpha beta gamma";
4049            let (state, cx) = setup(text, cx);
4050
4051            let word = position(&state, text, 7, cx);
4052            press(word, 2, false, cx);
4053            release(word, 2, cx);
4054            let after = position(&state, text, 13, cx);
4055            press(after, 1, true, cx);
4056            release(after, 1, cx);
4057            assert_eq!(selected(&state, cx), "beta gamma");
4058            let before = position(&state, text, 1, cx);
4059            press(before, 1, true, cx);
4060            release(before, 1, cx);
4061            assert_eq!(selected(&state, cx), "alpha beta");
4062        }
4063    }
4064
4065    mod copy_before_paint {
4066        use super::*;
4067        use crate::{TextSelection, text::SelectionFormat};
4068
4069        const MARKDOWN: &str = "中文 **café**\n\nβeta `\u{2009}code\u{2009}` 👩‍💻\n\n終わり";
4070        const PLAIN: &str = "中文 café\nβeta \u{2009}code\u{2009} 👩‍💻\n終わり\n";
4071
4072        struct Root {
4073            state: Entity<TextViewState>,
4074            format: SelectionFormat,
4075            width: Pixels,
4076            scrollable: bool,
4077        }
4078
4079        impl Render for Root {
4080            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4081                div()
4082                    .w(self.width)
4083                    .when(self.scrollable, |el| el.h(px(160.)))
4084                    .child(crate::TextSelectionLayer)
4085                    .child(
4086                        TextView::new(&self.state)
4087                            .scrollable(self.scrollable)
4088                            .selection_format(self.format),
4089                    )
4090            }
4091        }
4092
4093        fn setup(
4094            format: SelectionFormat,
4095            cx: &mut TestAppContext,
4096        ) -> (Entity<TextViewState>, &mut VisualTestContext) {
4097            cx.update(crate::init);
4098            let (root, cx) = cx.add_window_view(|_, cx| Root {
4099                state: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
4100                format,
4101                width: px(520.),
4102                scrollable: false,
4103            });
4104            cx.run_until_parked();
4105            cx.update(|window, cx| window.draw(cx).clear());
4106            (root.read_with(cx, |root, _| root.state.clone()), cx)
4107        }
4108
4109        fn document<'a>(
4110            markdown: &str,
4111            format: SelectionFormat,
4112            scrollable: bool,
4113            cx: &'a mut TestAppContext,
4114        ) -> (Entity<Root>, &'a mut VisualTestContext) {
4115            cx.update(crate::init);
4116            let (root, cx) = cx.add_window_view(|_, cx| Root {
4117                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
4118                format,
4119                width: px(520.),
4120                scrollable,
4121            });
4122            cx.run_until_parked();
4123            cx.update(|window, cx| window.draw(cx).clear());
4124            (root, cx)
4125        }
4126
4127        fn scroll_to(state: &Entity<TextViewState>, ix: usize, cx: &mut VisualTestContext) {
4128            state.read_with(cx, |state, _| {
4129                state.list_state.scroll_to(wgpui::ListOffset {
4130                    item_ix: ix,
4131                    offset_in_item: px(0.),
4132                })
4133            });
4134            cx.update(|window, cx| window.draw(cx).clear());
4135        }
4136
4137        fn endpoints(
4138            state: &Entity<TextViewState>,
4139            cx: &mut VisualTestContext,
4140        ) -> (
4141            wgpui::Point<Pixels>,
4142            wgpui::Point<Pixels>,
4143            wgpui::Point<Pixels>,
4144        ) {
4145            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
4146            let first = rows.first().unwrap();
4147            let last = rows.last().unwrap();
4148            (
4149                point(first.left() + px(0.1), first.center().y),
4150                point(first.right() - px(0.1), first.center().y),
4151                point(last.right() - px(0.1), last.center().y),
4152            )
4153        }
4154
4155        // Raw dispatch is intentional: simulate_event may draw after each
4156        // packet, concealing the exact native before-paint race.
4157        fn press(position: wgpui::Point<Pixels>, window: &mut Window, cx: &mut wgpui::App) {
4158            window.dispatch_event(
4159                wgpui::PlatformInput::MouseDown(MouseDownEvent {
4160                    position,
4161                    button: MouseButton::Left,
4162                    click_count: 1,
4163                    ..Default::default()
4164                }),
4165                cx,
4166            );
4167        }
4168
4169        fn extend(position: wgpui::Point<Pixels>, window: &mut Window, cx: &mut wgpui::App) {
4170            window.dispatch_event(
4171                wgpui::PlatformInput::MouseMove(wgpui::MouseMoveEvent {
4172                    position,
4173                    pressed_button: Some(MouseButton::Left),
4174                    ..Default::default()
4175                }),
4176                cx,
4177            );
4178        }
4179
4180        fn release(position: wgpui::Point<Pixels>, window: &mut Window, cx: &mut wgpui::App) {
4181            window.dispatch_event(
4182                wgpui::PlatformInput::MouseUp(MouseUpEvent {
4183                    position,
4184                    button: MouseButton::Left,
4185                    modifiers: Modifiers::default(),
4186                    click_count: 1,
4187                }),
4188                cx,
4189            );
4190        }
4191
4192        fn assert_copy(expected: &str, window: &mut Window, cx: &mut wgpui::App) {
4193            // Dispatch synchronously on the native current focus, without
4194            // focusing a different entity or using deferred window dispatch.
4195            let focus = window.focused(cx).expect("gesture focuses TextView");
4196            focus.dispatch_action(&crate::input::Copy, window, cx);
4197            assert_eq!(
4198                cx.read_from_clipboard().and_then(|item| item.text()),
4199                Some(expected.trim().to_string())
4200            );
4201            assert!(focus.is_focused(window));
4202            assert_eq!(TextSelection::selected_text(window, cx), expected);
4203        }
4204
4205        #[wgpui::test]
4206        fn custom_inline_and_block_copy_project_with_the_text(cx: &mut TestAppContext) {
4207            struct CustomRoot {
4208                state: Entity<TextViewState>,
4209                format: SelectionFormat,
4210                extensions: crate::text::MarkdownExtensions,
4211            }
4212            impl Render for CustomRoot {
4213                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4214                    div().w(px(520.)).child(crate::TextSelectionLayer).child(
4215                        TextView::new(&self.state)
4216                            .selection_format(self.format)
4217                            .markdown_extensions(self.extensions.clone()),
4218                    )
4219                }
4220            }
4221            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
4222                cx.update(crate::init);
4223                let extensions = crate::text::MarkdownExtensions::default()
4224                    .plugin(
4225                        crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(
4226                            |node, _| {
4227                                let markdown::mdast::Node::InlineMath(math) = node else {
4228                                    return None;
4229                                };
4230                                Some(
4231                                    crate::text::MarkdownNode::new("math", ())
4232                                        .text(format!("{}²", math.value)),
4233                                )
4234                            },
4235                        ),
4236                    )
4237                    .block_parser(|node, _| {
4238                        matches!(node, markdown::mdast::Node::ThematicBreak(_)).then(|| {
4239                            crate::text::MarkdownNode::new("block", ())
4240                                .text("BLOCK")
4241                                .markdown("---")
4242                        })
4243                    })
4244                    .block_renderer("block", |_, _, _| {
4245                        div()
4246                            .debug_selector(|| "copy-custom-block".into())
4247                            .w(px(520.))
4248                            .h(px(40.))
4249                    });
4250                let (root, cx) = cx.add_window_view(|_, cx| CustomRoot {
4251                    state: cx
4252                        .new(|cx| TextViewState::markdown("before $x$ after\n\n---\n\nlast", cx)),
4253                    format,
4254                    extensions,
4255                });
4256                cx.run_until_parked();
4257                cx.update(|window, cx| window.draw(cx).clear());
4258                let state = root.read_with(cx, |root, _| root.state.clone());
4259                let (start, _, end) = endpoints(&state, cx);
4260                let expected = if format == SelectionFormat::Plain {
4261                    "before x² after\nBLOCK\nlast\n"
4262                } else {
4263                    "before $x$ after\n\n---\n\nlast"
4264                };
4265                cx.update(|window, cx| {
4266                    press(start, window, cx);
4267                    extend(end, window, cx);
4268                    assert_copy(expected, window, cx);
4269                    release(end, window, cx);
4270                });
4271                cx.update(|window, cx| window.draw(cx).clear());
4272                cx.update(|window, cx| assert_copy(expected, window, cx));
4273                let block = cx.debug_bounds("copy-custom-block").unwrap();
4274                cx.update(|window, cx| {
4275                    press(block.center(), window, cx);
4276                    extend(point(block.center().x, block.bottom() + px(1.)), window, cx);
4277                    assert_copy(
4278                        if format == SelectionFormat::Plain {
4279                            "BLOCK\n"
4280                        } else {
4281                            "---"
4282                        },
4283                        window,
4284                        cx,
4285                    );
4286                });
4287            }
4288        }
4289
4290        #[wgpui::test]
4291        fn unicode_180_paragraph_copy_extends_and_retracts_before_paint(cx: &mut TestAppContext) {
4292            let markdown = (0..180)
4293                .map(|ix| format!("p{ix:03} **café** 中文 👩‍💻 `\u{2009}code\u{2009}`"))
4294                .collect::<Vec<_>>()
4295                .join("\n\n");
4296            // Expected bytes are constructed independently of rendered_text(),
4297            // selected_text(), and the document's selection serializer.
4298            let expected = (0..180)
4299                .map(|ix| format!("p{ix:03} café 中文 👩‍💻 \u{2009}code\u{2009}\n"))
4300                .collect::<String>();
4301            let (root, cx) = document(&markdown, SelectionFormat::Plain, false, cx);
4302            cx.simulate_resize(wgpui::size(px(800.), px(12000.)));
4303            cx.update(|window, cx| window.draw(cx).clear());
4304            let state = root.read_with(cx, |root, _| root.state.clone());
4305            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
4306            let first = rows.first().unwrap();
4307            let first_end = rows
4308                .iter()
4309                .take_while(|row| row.top() < first.bottom())
4310                .last()
4311                .unwrap();
4312            let last = rows.last().unwrap();
4313            assert!(last.top() > first.top() + px(3000.));
4314            let start = point(first.left() + px(0.1), first.center().y);
4315            let short_end = point(first_end.right() - px(0.1), first_end.center().y);
4316            let end = point(last.right() - px(0.1), last.center().y);
4317            let short = "p000 café 中文 👩‍💻 \u{2009}code\u{2009}\n";
4318            cx.update(|window, cx| {
4319                press(start, window, cx);
4320                extend(short_end, window, cx);
4321                assert_copy(short, window, cx);
4322            });
4323            cx.update(|window, cx| window.draw(cx).clear());
4324            cx.update(|window, cx| {
4325                extend(end, window, cx);
4326                assert_copy(&expected, window, cx);
4327                extend(short_end, window, cx);
4328                assert_copy(short, window, cx);
4329            });
4330        }
4331
4332        #[wgpui::test]
4333        fn scrolling_before_paint_keeps_the_completed_frame_coordinates(cx: &mut TestAppContext) {
4334            let markdown = format!(
4335                "{}\n\nlast",
4336                "alpha beta gamma delta epsilon zeta ".repeat(30)
4337            );
4338            let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
4339            root.update(cx, |root, cx| {
4340                root.width = px(180.);
4341                cx.notify();
4342            });
4343            cx.update(|window, cx| window.draw(cx).clear());
4344            let state = root.read_with(cx, |root, _| root.state.clone());
4345            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
4346            let first = rows[0];
4347            let (start, end) = state.read_with(cx, |state, _| {
4348                (
4349                    state.selection_adapter.first_text_position(0),
4350                    state.selection_adapter.first_text_position("alpha".len()),
4351                )
4352            });
4353            cx.update(|window, cx| {
4354                press(start, window, cx);
4355                extend(end, window, cx);
4356            });
4357            cx.update(|window, cx| window.draw(cx).clear());
4358            cx.update(|window, cx| {
4359                state.read(cx).list_state.scroll_by(first.size.height);
4360                // The logical offset changed, registration and native pixels
4361                // have not. This must not select the next wrapped row.
4362                assert_copy("alpha\n", window, cx);
4363            });
4364        }
4365
4366        #[wgpui::test]
4367        fn offscreen_remeasurement_is_not_a_copy_projection(cx: &mut TestAppContext) {
4368            let markdown = (0..180)
4369                .map(|ix| format!("row {ix:03} café 中文"))
4370                .collect::<Vec<_>>()
4371                .join("\n\n");
4372            let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
4373            let state = root.read_with(cx, |root, _| root.state.clone());
4374            scroll_to(&state, 90, cx);
4375            root.update(cx, |root, cx| {
4376                root.width = px(260.);
4377                cx.notify();
4378            });
4379            cx.update(|window, cx| window.draw(cx).clear());
4380            scroll_to(&state, 90, cx);
4381            // measure_all has remeasured earlier, unpainted paragraphs at the
4382            // new width. Only this completed paint supplies Copy geometry.
4383            let (start, end, _) = endpoints(&state, cx);
4384            cx.update(|window, cx| {
4385                press(start, window, cx);
4386                extend(end, window, cx);
4387                assert_copy("row 090 café 中文\n", window, cx);
4388            });
4389        }
4390
4391        #[wgpui::test]
4392        fn virtualized_flow_retains_its_source_owned_partial_anchor(cx: &mut TestAppContext) {
4393            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
4394                let tail = (1..180)
4395                    .map(|ix| format!("row {ix:03} café 中文"))
4396                    .collect::<Vec<_>>();
4397                let markdown = format!("PREFIX `code` suffix\n\n{}", tail.join("\n\n"));
4398                let expected = if format == SelectionFormat::Plain {
4399                    format!("code suffix\n{}\n", tail.join("\n"))
4400                } else {
4401                    format!("`code` suffix\n\n{}", tail.join("\n\n"))
4402                };
4403                let (root, cx) = document(&markdown, format, true, cx);
4404                let state = root.read_with(cx, |root, _| root.state.clone());
4405                let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
4406                let code = rows[1];
4407                let suffix = rows[2];
4408                assert!(code.left() < suffix.left());
4409                cx.update(|window, cx| {
4410                    press(point(code.left() + px(0.1), code.center().y), window, cx);
4411                    extend(
4412                        point(suffix.right() - px(0.1), suffix.center().y),
4413                        window,
4414                        cx,
4415                    );
4416                });
4417                cx.update(|window, cx| window.draw(cx).clear());
4418                scroll_to(&state, 179, cx);
4419                // Two completed frames let GPUI retire temporary flow fragments.
4420                cx.update(|window, cx| window.draw(cx).clear());
4421                let (_, _, end) = endpoints(&state, cx);
4422                cx.update(|window, cx| {
4423                    extend(end, window, cx);
4424                    assert_copy(&expected, window, cx);
4425                });
4426            }
4427        }
4428
4429        #[wgpui::test]
4430        fn a_new_range_copies_before_its_first_selection_paint(cx: &mut TestAppContext) {
4431            let (state, cx) = setup(SelectionFormat::Plain, cx);
4432            let (start, _, end) = endpoints(&state, cx);
4433            cx.update(|window, cx| {
4434                press(start, window, cx);
4435                extend(end, window, cx);
4436                assert_copy(PLAIN, window, cx);
4437            });
4438        }
4439
4440        #[wgpui::test]
4441        fn an_established_range_extends_and_retracts_without_paint(cx: &mut TestAppContext) {
4442            let (state, cx) = setup(SelectionFormat::Plain, cx);
4443            let (start, first_end, end) = endpoints(&state, cx);
4444            cx.update(|window, cx| {
4445                press(start, window, cx);
4446                extend(first_end, window, cx);
4447            });
4448            cx.update(|window, cx| window.draw(cx).clear());
4449            cx.update(|window, cx| {
4450                assert_copy("中文 café\n", window, cx);
4451                extend(end, window, cx);
4452                assert_copy(PLAIN, window, cx);
4453                extend(first_end, window, cx);
4454                assert_copy("中文 café\n", window, cx);
4455            });
4456        }
4457
4458        #[wgpui::test]
4459        fn source_copy_projects_the_current_range_without_paint(cx: &mut TestAppContext) {
4460            let (state, cx) = setup(SelectionFormat::Source, cx);
4461            let (start, first_end, end) = endpoints(&state, cx);
4462            cx.update(|window, cx| {
4463                press(start, window, cx);
4464                extend(first_end, window, cx);
4465                assert_copy("中文 **café**", window, cx);
4466                extend(end, window, cx);
4467                assert_copy(MARKDOWN, window, cx);
4468                extend(first_end, window, cx);
4469                assert_eq!(TextSelection::selected_text(window, cx), "中文 **café**");
4470            });
4471        }
4472
4473        #[wgpui::test]
4474        fn a_blank_gesture_does_not_reuse_the_previous_range(cx: &mut TestAppContext) {
4475            let (state, cx) = setup(SelectionFormat::Plain, cx);
4476            let (start, first_end, end) = endpoints(&state, cx);
4477            cx.update(|window, cx| {
4478                press(start, window, cx);
4479                extend(end, window, cx);
4480                assert_eq!(TextSelection::selected_text(window, cx), PLAIN);
4481                release(end, window, cx);
4482                press(first_end + point(px(20.), px(0.)), window, cx);
4483                extend(first_end + point(px(60.), px(0.)), window, cx);
4484                assert_eq!(TextSelection::selected_text(window, cx), "");
4485            });
4486        }
4487
4488        #[wgpui::test]
4489        fn replacing_source_cannot_reproject_old_content(cx: &mut TestAppContext) {
4490            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
4491                for replacement in ["replacement".to_string(), "replacement ".repeat(500)] {
4492                    let (state, cx) = setup(format, cx);
4493                    let (start, _, end) = endpoints(&state, cx);
4494                    cx.update(|window, cx| {
4495                        press(start, window, cx);
4496                        extend(end, window, cx);
4497                        assert_eq!(
4498                            TextSelection::selected_text(window, cx),
4499                            if format == SelectionFormat::Plain {
4500                                PLAIN
4501                            } else {
4502                                MARKDOWN
4503                            }
4504                        );
4505                        // Large replacements leave the previous parsed document
4506                        // in place while parsing; neither size may reuse it.
4507                        state.update(cx, |state, cx| state.set_text(&replacement, cx));
4508                        assert_eq!(TextSelection::selected_text(window, cx), "");
4509                    });
4510                }
4511            }
4512        }
4513    }
4514
4515    // Regression: markdown `TextView` items inside an outer `wgpui::list` with
4516    // `measure_all` must keep a stable total content height while scrolling.
4517    // Before synchronous full-replace parsing, off-screen markdown views were
4518    // first measured with empty content and the scrollbar thumb jittered as the
4519    // total height grew during scrolling.
4520    #[wgpui::test]
4521    fn outer_list_content_total_stable_while_scrolling(cx: &mut TestAppContext) {
4522        use wgpui::{ListAlignment, ListState, list};
4523
4524        const ITEMS: &[&str] = &[
4525            "# Heading\n\nA paragraph long enough to wrap across several lines and produce a non-trivial height.",
4526            "Short.",
4527            "Paragraph A\n\nParagraph B\n\nParagraph C with more words to increase the height.",
4528            "## Subheading\n\n- One\n- Two\n- Three\n\nClosing paragraph.",
4529            "Only one line.",
4530            "**Bold**: medium length text with `code` mixed with regular words.",
4531            "1. First\n2. Second\n3. Third\n\nA short closing paragraph.",
4532            "A long message with enough words to wrap across multiple lines, create a taller item, and verify that off-screen measurement matches visible measurement.",
4533        ];
4534        let n = 40usize;
4535
4536        struct ListRoot {
4537            state: ListState,
4538        }
4539        impl Render for ListRoot {
4540            fn render(&mut self, _w: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4541                div().w(px(360.)).h(px(500.)).child(
4542                    list(self.state.clone(), |ix, _w, _cx| {
4543                        div()
4544                            .w_full()
4545                            .child(TextView::markdown(
4546                                ("md", ix as u64),
4547                                ITEMS[ix % ITEMS.len()],
4548                            ))
4549                            .into_any_element()
4550                    })
4551                    .size_full(),
4552                )
4553            }
4554        }
4555
4556        cx.update(crate::init);
4557        let state = ListState::new(n, ListAlignment::Top, px(2048.)).measure_all();
4558        let probe = state.clone();
4559        let (_view, cx) = cx.add_window_view(|_w, _cx| ListRoot { state });
4560        let cx: &mut VisualTestContext = cx;
4561
4562        cx.run_until_parked();
4563        cx.update(|w, cx| {
4564            let _ = w.draw(cx);
4565        });
4566        cx.run_until_parked();
4567        cx.update(|w, cx| {
4568            let _ = w.draw(cx);
4569        });
4570
4571        let total = |p: &ListState| {
4572            f32::from(p.max_offset_for_scrollbar().height + p.viewport_bounds().size.height)
4573        };
4574        let mut totals = vec![total(&probe)];
4575        for _ in 0..20 {
4576            probe.scroll_by(px(150.));
4577            cx.update(|w, cx| {
4578                let _ = w.draw(cx);
4579            });
4580            cx.run_until_parked();
4581            totals.push(total(&probe));
4582        }
4583        let min = totals.iter().cloned().fold(f32::INFINITY, f32::min);
4584        let max = totals.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4585        println!(
4586            "OUTER_LIST_PROBE min={min:.1} max={max:.1} delta={:.1}",
4587            max - min
4588        );
4589        assert!(
4590            (max - min) < 2.0,
4591            "list content total jittered while scrolling: min={min} max={max} totals={totals:?}"
4592        );
4593    }
4594}