Skip to main content

wgpui_base/text/
state.rs

1use futures::Stream as _;
2#[cfg(not(target_family = "wasm"))]
3use std::time::Instant;
4use std::{
5    ops::{Range, RangeInclusive},
6    pin::Pin,
7    sync::{Arc, Mutex, OnceLock},
8    task::Poll,
9    time::Duration,
10};
11#[cfg(target_family = "wasm")]
12use web_time::Instant;
13
14use wgpui::{
15    App, AppContext as _, Bounds, Context, EntityId, FocusHandle, IntoElement, KeyBinding,
16    ListState, ParentElement as _, Pixels, Point, Render, SharedString, Styled as _, Task, Window,
17    prelude::FluentBuilder as _, px,
18};
19
20use crate::{
21    AutoScroll, ElementExt, TextSelection,
22    async_util::{Receiver, Sender, unbounded},
23    input::{self, SelectAll},
24    text::{
25        CodeBlockActionsFn, CodeBlockHighlighterFn, LinkClickHandlerFn, MarkdownExtensions,
26        RangeHighlight, RangeHighlightError, RenderedText, TableActionsFn, TextViewStyle,
27        document::ParsedDocument,
28        format,
29        node::{self, NodeContext},
30        range_highlight::{
31            LeafRemap, PendingReveal, RangeHighlightFrame, RenderedIndex, RevealRequest,
32        },
33        selection_adapter::TextViewSelectionAdapter,
34        stream_fade::{StreamFadeTracker, TextViewMotion},
35    },
36    touch_selection::caret_line_box,
37    v_flex,
38};
39
40const CONTEXT: &'static str = "TextView";
41// Keep coalescing bounded so sustained streams still render intermediate updates.
42const MAX_COALESCED_UPDATES_PER_PARSE: usize = 64;
43// Preserve exact first-layout height for small documents while bounding the
44// amount of source parsed synchronously on the UI thread.
45const MAX_SYNC_FULL_REPLACE_BYTES: usize = 4 * 1024;
46// Repaint a streamed fade at about 30 fps, not at the display refresh rate.
47const STREAM_FADE_TICK: Duration = Duration::from_millis(33);
48
49pub(crate) fn init(cx: &mut App) {
50    cx.bind_keys(vec![
51        #[cfg(target_os = "macos")]
52        KeyBinding::new("cmd-c", input::Copy, Some(CONTEXT)),
53        #[cfg(not(target_os = "macos"))]
54        KeyBinding::new("ctrl-c", input::Copy, Some(CONTEXT)),
55        #[cfg(target_os = "macos")]
56        KeyBinding::new("cmd-a", input::SelectAll, Some(CONTEXT)),
57        #[cfg(not(target_os = "macos"))]
58        KeyBinding::new("ctrl-a", input::SelectAll, Some(CONTEXT)),
59    ]);
60}
61
62/// The content format of the text view.
63#[derive(Clone, Copy, PartialEq, Eq)]
64pub(super) enum TextViewFormat {
65    /// Markdown view
66    Markdown,
67    /// HTML view
68    Html,
69}
70
71/// The format of the text returned by
72/// [`TextViewState::selected_text`], which is also what copy writes to the
73/// clipboard.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub enum SelectionFormat {
76    /// The rendered text, without any markup.
77    #[default]
78    Plain,
79    /// The source of the selection.
80    ///
81    /// Select-all returns the original source verbatim, a partial selection is
82    /// reconstructed as Markdown from the parsed nodes (e.g. selecting inside
83    /// a `**bold**` run yields `**bold**`).
84    Source,
85    /// The rendered text while the selection stays within one style, the
86    /// source as soon as it takes in several.
87    ///
88    /// A style is everything the source would spell out around the selected
89    /// text: the marks of an inline run (emphasis, code, a link's URL) and the
90    /// block it sits in (a heading's `#`, a list marker, a code fence). So
91    /// selecting inside a `**bold**` run, a link or a code block yields the
92    /// text alone, also when the selection reaches exactly up to the run's
93    /// boundaries, while a selection across that boundary, into a second
94    /// block, or over an inline object copies like [`Self::Source`]. Two blocks
95    /// count as two styles even when their marks match, since the source of
96    /// either spells out where one ends. Select-all copies the source verbatim.
97    SourceAcrossStyles,
98}
99
100/// One text element's laid-out vertical extent, reported by `Inline` during
101/// prepaint so `TextView` can snap its `max_lines` clip to a whole-line
102/// boundary.
103#[derive(Clone, Copy)]
104pub(super) struct LineSpan {
105    pub(super) top: Pixels,
106    pub(super) bottom: Pixels,
107    pub(super) line_height: Pixels,
108}
109
110/// The state of a TextView.
111pub struct TextViewState {
112    entity_id: EntityId,
113    pub(super) focus_handle: FocusHandle,
114    pub(super) list_state: ListState,
115
116    /// The bounds of the text view
117    bounds: Bounds<Pixels>,
118
119    pub(super) selectable: bool,
120    pub(super) selection_format: SelectionFormat,
121    pub(super) scrollable: bool,
122    pub(super) max_lines: Option<usize>,
123    /// Line spans reported by `Inline` during prepaint (collected only while
124    /// [`Self::max_lines`] is set); cleared by `TextView` at each frame start.
125    pub(super) line_spans: Arc<Mutex<Vec<LineSpan>>>,
126    /// Whether the last painted frame clipped content due to `max_lines`.
127    pub(super) clamped: bool,
128    pub(super) text_view_style: Arc<TextViewStyle>,
129    pub(super) code_block_actions: Option<std::sync::Arc<CodeBlockActionsFn>>,
130    pub(super) code_block_highlighter: Option<std::sync::Arc<CodeBlockHighlighterFn>>,
131    pub(super) table_actions: Option<std::sync::Arc<TableActionsFn>>,
132    pub(super) image_source: Option<std::sync::Arc<super::text_view::ImageSourceFn>>,
133    pub(super) link_click_handler: Option<std::sync::Arc<LinkClickHandlerFn>>,
134    pub(super) markdown_extensions: Arc<MarkdownExtensions>,
135
136    pub(super) is_selecting: bool,
137    /// Logical ranges retained across compatible resource or presentation reflow.
138    pub(super) preserve_inline_selection: bool,
139    multi_click_selection: Option<TextViewMultiClickSelection>,
140    selected_text_override: Option<String>,
141    select_all: bool,
142    pub(super) auto_scroll: AutoScroll,
143    pub(super) selection_adapter: TextViewSelectionAdapter,
144
145    pub(super) parsed_content: ParsedContent,
146    pub(super) stream_fade: StreamFadeTracker,
147    fade_tick: Option<Task<()>>,
148    /// Content format (markdown / html), used for bounded synchronous parsing
149    /// of small full-replace updates.
150    format: TextViewFormat,
151    text: String,
152    /// The text a `TextView` element last handed over, to recognize the same
153    /// string next frame without comparing its bytes.
154    element_text: Option<SharedString>,
155    revision: usize,
156    /// The revision of the update `parsed_content` was committed from.
157    committed_revision: usize,
158    /// The revision of the last update that replaced the text rather than
159    /// appending to it.
160    full_update_revision: usize,
161    /// The rendered text of `parsed_content`, built when first read.
162    rendered_index: Arc<OnceLock<RenderedIndex>>,
163    range_highlights: Option<Arc<RangeHighlightFrame>>,
164    pub(super) pending_reveal: Option<PendingReveal>,
165    pub(super) selection_revision: usize,
166    compatible_layout_update: bool,
167    layout_text_style: Option<(wgpui::TextStyle, Pixels, f32)>,
168    parsed_error: Option<SharedString>,
169    tx: Sender<UpdateOptions>,
170    _parse_task: Task<()>,
171    _receive_task: Task<()>,
172}
173
174impl TextViewState {
175    /// Create a Markdown TextViewState.
176    pub fn markdown(text: &str, cx: &mut Context<Self>) -> Self {
177        Self::new(TextViewFormat::Markdown, text, cx)
178    }
179
180    /// Create a HTML TextViewState.
181    pub fn html(text: &str, cx: &mut Context<Self>) -> Self {
182        Self::new(TextViewFormat::Html, text, cx)
183    }
184
185    /// Create a new TextViewState.
186    fn new(format: TextViewFormat, text: &str, cx: &mut Context<Self>) -> Self {
187        let focus_handle = cx.focus_handle();
188        let selection_adapter = TextViewSelectionAdapter::new(cx.entity().downgrade(), cx);
189
190        let (tx, rx) = unbounded::<UpdateOptions>();
191        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
192        let _receive_task = cx.spawn({
193            async move |weak_self, cx| {
194                while let Ok(parsed_update) = rx_result.recv().await {
195                    // A result that commits nothing — the background parser
196                    // acknowledging a synchronous parse — leaves the state
197                    // alone: updating it would tell the retained
198                    // views that read it that it changed.
199                    let Ok(commits) =
200                        weak_self.read_with(cx, |state, _| state.commits(&parsed_update))
201                    else {
202                        break;
203                    };
204                    if !commits {
205                        continue;
206                    }
207                    _ = weak_self.update(cx, |state, cx| {
208                        state.commit_parsed_update(parsed_update, cx);
209                    });
210                }
211            }
212        });
213
214        let _parse_task = cx.background_spawn(UpdateFuture::new(format, rx, tx_result));
215
216        let mut this = Self {
217            entity_id: cx.entity_id(),
218            focus_handle,
219            bounds: Bounds::default(),
220            multi_click_selection: None,
221            selected_text_override: None,
222            select_all: false,
223            selectable: false,
224            selection_format: SelectionFormat::default(),
225            scrollable: false,
226            max_lines: None,
227            line_spans: Arc::default(),
228            clamped: false,
229            // Measure all blocks (not just visible ones) so the scrollbar
230            // thumb size stays stable. Without this, off-screen blocks count
231            // as zero height until scrolled into view, which makes the
232            // scrollbar jitter as more blocks get measured during scrolling.
233            list_state: ListState::new(0, wgpui::ListAlignment::Top, px(1000.)).measure_all(),
234            text_view_style: Arc::default(),
235            code_block_actions: None,
236            code_block_highlighter: None,
237            table_actions: None,
238            link_click_handler: None,
239            image_source: None,
240            markdown_extensions: Arc::default(),
241            is_selecting: false,
242            preserve_inline_selection: false,
243            auto_scroll: AutoScroll::default(),
244            selection_adapter,
245            parsed_content: Default::default(),
246            stream_fade: StreamFadeTracker::default(),
247            fade_tick: None,
248            format,
249            parsed_error: None,
250            text: text.to_string(),
251            element_text: None,
252            revision: 0,
253            committed_revision: 0,
254            full_update_revision: 0,
255            rendered_index: Arc::default(),
256            range_highlights: None,
257            pending_reveal: None,
258            selection_revision: 0,
259            compatible_layout_update: false,
260            layout_text_style: None,
261            tx,
262            _parse_task,
263            _receive_task,
264        };
265        this.increment_update(&text, false, cx);
266        this
267    }
268
269    /// Get the text content.
270    pub(crate) fn source(&self) -> SharedString {
271        self.parsed_content.document.source.clone()
272    }
273
274    /// Set whether the text is selectable, default false.
275    pub fn selectable(mut self, selectable: bool) -> Self {
276        self.selectable = selectable;
277        self
278    }
279
280    /// Set whether the text is selectable, default false.
281    pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
282        self.selectable = selectable;
283        cx.notify();
284    }
285
286    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
287    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
288        self.selection_format = selection_format;
289        self
290    }
291
292    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
293    pub fn set_selection_format(
294        &mut self,
295        selection_format: SelectionFormat,
296        cx: &mut Context<Self>,
297    ) {
298        self.selection_format = selection_format;
299        cx.notify();
300    }
301
302    /// Set whether the text view scrolls internally, default false.
303    pub fn scrollable(mut self, scrollable: bool) -> Self {
304        self.scrollable = scrollable;
305        self
306    }
307
308    /// Set whether the text view scrolls internally, default false.
309    pub fn set_scrollable(&mut self, scrollable: bool, cx: &mut Context<Self>) {
310        if !scrollable {
311            self.reset_selection_and_adapter(cx);
312        }
313        self.scrollable = scrollable;
314        cx.notify();
315    }
316
317    /// Whether the last painted frame clipped content because of
318    /// [`TextView::max_lines`](crate::text::TextView::max_lines).
319    pub fn is_clamped(&self) -> bool {
320        self.clamped
321    }
322
323    /// Set the text content.
324    ///
325    /// Markdown that extends the current non-empty text is appended like
326    /// [`Self::push_str`], keeping the selection; any other text replaces it.
327    /// With a streamed fade-in enabled, extended text fades in; a replacement
328    /// shows at once.
329    pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
330        if self.text.as_str() == text {
331            return;
332        }
333        // HTML blocks carry no spans, so an append would parse the delta as a
334        // standalone document. After a failed parse the background parser's
335        // document lacks that text, so only a full parse resynchronizes it.
336        if self.format == TextViewFormat::Markdown
337            && self.parsed_error.is_none()
338            && !self.text.is_empty()
339            && let Some(delta) = text.strip_prefix(self.text.as_str())
340        {
341            self.push_str(delta, cx);
342            return;
343        }
344        self.stream_fade.note_replace();
345
346        self.text.clear();
347        self.text.push_str(text);
348        self.parsed_error = None;
349        self.increment_update(text, false, cx);
350    }
351
352    /// [`Self::set_text`] for the text a `TextView` element hands over every
353    /// frame: the string it handed over last time (the same allocation, not
354    /// merely equal bytes) is recognized without a comparison, as long as the
355    /// state still holds a text of its length.
356    pub(super) fn set_element_text(&mut self, text: &SharedString, cx: &mut Context<Self>) {
357        let same_string = self.element_text.as_ref().is_some_and(|current| {
358            current.as_ptr() == text.as_ptr() && current.len() == text.len()
359        });
360        if same_string && self.text.len() == text.len() {
361            return;
362        }
363        self.element_text = Some(text.clone());
364        self.set_text(text, cx);
365    }
366
367    /// Append partial text content to the existing text.
368    pub fn push_str(&mut self, new_text: &str, cx: &mut Context<Self>) {
369        if new_text.is_empty() {
370            return;
371        }
372        self.stream_fade.note_extend(self.text.len());
373        self.text.push_str(new_text);
374        self.increment_update(new_text, true, cx);
375    }
376
377    /// Set the motion policy; see [`TextViewMotion`].
378    pub fn motion(mut self, motion: TextViewMotion) -> Self {
379        self.set_motion(motion);
380        self
381    }
382
383    /// Set the motion policy; see [`TextViewMotion`].
384    pub fn set_motion(&mut self, motion: TextViewMotion) {
385        self.stream_fade.set_motion(motion);
386    }
387
388    pub(crate) fn set_markdown_extensions(
389        &mut self,
390        markdown_extensions: Arc<MarkdownExtensions>,
391        cx: &mut Context<Self>,
392    ) {
393        if self.markdown_extensions.revision() == markdown_extensions.revision() {
394            return;
395        }
396
397        let parser_configuration_changed = !self
398            .markdown_extensions
399            .has_same_parser_configuration(&markdown_extensions);
400        self.markdown_extensions = markdown_extensions;
401        if parser_configuration_changed && self.format == TextViewFormat::Markdown {
402            let text = self.text.clone();
403            self.increment_update(&text, false, cx);
404        }
405    }
406
407    /// Return the selected text, in the view's [`SelectionFormat`].
408    pub fn selected_text(&self) -> String {
409        self.selected_text_in(None)
410    }
411
412    /// Return the original Markdown source byte range corresponding to the
413    /// rendered selection.
414    ///
415    /// The range addresses the source passed to this Markdown TextView. It is
416    /// derived from parser positions retained by the rendered inline nodes, so
417    /// identical rendered text maps to the occurrence that was actually
418    /// selected. The result is one contiguous source range, so it includes any
419    /// Markdown delimiters between the selected rendered endpoints. HTML views
420    /// and selections without an exact source mapping return `None`. Select-all
421    /// in a Markdown view returns the full source range.
422    pub fn selected_source_range(&self) -> Option<Range<usize>> {
423        if self.format != TextViewFormat::Markdown {
424            return None;
425        }
426        if self.select_all {
427            return Some(0..self.source().len());
428        }
429        self.parsed_content.document.selected_source_range()
430    }
431
432    /// The format to copy in, which is [`SelectionFormat::Plain`] whenever the
433    /// requested one cannot be produced.
434    ///
435    /// Only a Markdown view can return source. Reconstructing HTML would mean
436    /// spelling every attribute back out — a mark's color, an image's
437    /// dimensions, a cell's alignment — with a new way to lose one at each
438    /// step, and html5ever records no source offsets to fall back on (it
439    /// reports only line numbers), so there is no original text to copy from
440    /// either.
441    fn effective_format(&self) -> SelectionFormat {
442        match self.format {
443            TextViewFormat::Markdown => self.selection_format,
444            TextViewFormat::Html => SelectionFormat::Plain,
445        }
446    }
447
448    /// A pending full replacement leaves the previous document on screen, but
449    /// that document must no longer supply clipboard content.
450    pub(super) fn has_current_copy_document(&self) -> bool {
451        self.committed_revision >= self.full_update_revision
452    }
453
454    /// Return the selected text, with `blocks` bounding which top-level blocks
455    /// the selection covers.
456    ///
457    /// The range comes from the selection endpoints, which know their block
458    /// even after it scrolls out of view; see
459    /// [`ParsedDocument::selected_text`](crate::text::document::ParsedDocument).
460    pub(super) fn selected_text_in(&self, blocks: Option<RangeInclusive<usize>>) -> String {
461        let format = self.effective_format();
462
463        if self.select_all {
464            if format != SelectionFormat::Plain {
465                return self.source().to_string();
466            }
467
468            return self.parsed_content.document.text();
469        }
470
471        // A multi-click stores the plain text it selected, which is a shortcut
472        // past the block walk. Source mode cannot take it: the word it stored
473        // has lost its markup. The click also set the inline selection it came
474        // from, so the walk reconstructs the same range with the markup intact.
475        if format == SelectionFormat::Plain
476            && let Some(text) = &self.selected_text_override
477        {
478            return text.clone();
479        }
480
481        self.parsed_content.document.selected_text(format, blocks)
482    }
483
484    /// Force a full re-measure of the block list after the document has been
485    /// replaced.
486    ///
487    /// `Document::render_root` only calls `ListState::reset` when the block
488    /// *count* changes, and the full-measure pass enabled by `measure_all` is
489    /// a one-shot latch that only `reset`, `remeasure_items`, or a width
490    /// change re-arms. Replacing a document with one that happens to have the
491    /// same number of blocks therefore leaves every cached height belonging to
492    /// the *previous* document. The list summary height stays wrong, and since
493    /// the wheel clamps against that summary, the blocks past the false bottom
494    /// can never scroll into view to be re-measured -- the clamp seals itself.
495    ///
496    /// `remeasure_items` re-arms the latch and marks the items unmeasured
497    /// while keeping their old sizes as hints, so the scrollbar does not
498    /// collapse in the frame before the next layout measures the real heights.
499    fn invalidate_measured_heights(&self) {
500        let count = self.list_state.item_count();
501        if count > 0 {
502            self.list_state.remeasure_items(0..count);
503        }
504    }
505
506    /// Remeasure inline resources after their prepared content or metrics change.
507    ///
508    /// Call from the resource owner's completion handler, through a weak entity
509    /// when the task can outlive this view. This does not reparse the document.
510    /// Existing logical selection is retained until the next selection gesture.
511    pub fn invalidate_inline_layout(&mut self, cx: &mut Context<Self>) {
512        self.preserve_selection_for_reflow();
513        cx.notify();
514    }
515
516    pub(super) fn preserve_selection_for_reflow(&mut self) {
517        self.preserve_inline_selection = true;
518        self.compatible_layout_update = true;
519        self.invalidate_measured_heights();
520    }
521
522    fn increment_update(&mut self, text: &str, append: bool, cx: &mut Context<Self>) {
523        self.revision += 1;
524        if !append {
525            self.full_update_revision = self.revision;
526            self.selection_revision = self.selection_revision.wrapping_add(1);
527            // Old native layouts must not project a still-active gesture back
528            // into replaced content, including while a large parse is pending.
529            self.selection_adapter.clear_copy_projections(cx);
530            self.parsed_content.document.clear_selection();
531        }
532        let parse_synchronously = !append && text.len() <= MAX_SYNC_FULL_REPLACE_BYTES;
533        let update_options = UpdateOptions {
534            revision: self.revision,
535            append,
536            mode: if append {
537                ParseMode::Compatible
538            } else if parse_synchronously {
539                ParseMode::BaselineAck
540            } else {
541                ParseMode::Replace
542            },
543            pending_text: text.to_string(),
544            markdown_extensions: self.markdown_extensions.clone(),
545        };
546
547        // Keep small full replacements synchronous so their first layout has
548        // the exact content height. Larger replacements use the existing
549        // background parser, bounding synchronous parser input on the UI thread.
550        if parse_synchronously {
551            match parse_content(self.format, ParsedContent::default(), &update_options) {
552                Ok(content) => {
553                    self.reconcile_range_highlights(&content.document, self.revision, false);
554                    self.stream_fade.record(
555                        &self.parsed_content.document,
556                        &content.document,
557                        Instant::now(),
558                    );
559                    self.parsed_content = content;
560                    self.parsed_error = None;
561                    self.invalidate_measured_heights();
562                    if !self.is_selecting {
563                        self.reset_selection_and_adapter(cx);
564                    }
565                }
566                Err(err) => {
567                    self.stream_fade.discard_pending();
568                    self.parsed_error = Some(err);
569                }
570            }
571            // Keep the background parser's accumulated document in sync so a
572            // later append extends this baseline instead of parsing the delta
573            // as a standalone document.
574            _ = self.tx.try_send(update_options);
575            cx.notify();
576            return;
577        }
578
579        _ = self.tx.try_send(update_options);
580    }
581
582    /// Whether [`Self::commit_parsed_update`] commits `parsed_update`: it is
583    /// not older than what is committed or than the last replacement, nor
584    /// the background parser acknowledging a synchronous parse.
585    fn commits(&self, parsed_update: &ParsedUpdate) -> bool {
586        if parsed_update.revision < self.full_update_revision
587            || parsed_update.revision <= self.committed_revision
588        {
589            return false;
590        }
591        debug_assert!(!parsed_update.baseline_ack || parsed_update.full_parse);
592        !parsed_update.baseline_ack
593    }
594
595    /// Commit a result of the background parser.
596    ///
597    /// A stream that appends faster than a parse completes has always moved
598    /// past the revision the result was parsed from, so only discarding
599    /// results of an older revision would show nothing until the stream
600    /// stops. A result parsed since the text was last replaced is a prefix of
601    /// the current text and is committed; one from before that replacement,
602    /// or older than what is already committed, is discarded.
603    fn commit_parsed_update(&mut self, parsed_update: ParsedUpdate, cx: &mut Context<Self>) {
604        if !self.commits(&parsed_update) {
605            return;
606        }
607
608        match parsed_update.result {
609            Ok(content) => {
610                let append = parsed_update.selection_compatible && !parsed_update.full_parse;
611                if append && self.full_update_revision <= self.committed_revision {
612                    self.splice_appended_blocks(&content.document);
613                }
614                self.reconcile_range_highlights(&content.document, parsed_update.revision, append);
615                self.stream_fade.record(
616                    &self.parsed_content.document,
617                    &content.document,
618                    Instant::now(),
619                );
620                // This result may cover only part of the queued appends.
621                // Keep the uncommitted tail pending from this document's end,
622                // rather than consuming its fade with the earlier chunk.
623                if parsed_update.revision < self.revision {
624                    self.stream_fade.note_extend(content.document.source.len());
625                }
626                self.parsed_content = content;
627                self.parsed_error = None;
628                self.compatible_layout_update = parsed_update.selection_compatible;
629                if parsed_update.full_parse {
630                    self.invalidate_measured_heights();
631                }
632            }
633            Err(err) => {
634                self.stream_fade.discard_pending();
635                self.parsed_error = Some(err);
636            }
637        }
638        // Don't interrupt an active drag-selection; the stored
639        // positions remain valid for append-only updates and will
640        // self-correct on the next mouse-move event.
641        if !parsed_update.selection_compatible && !self.is_selecting {
642            self.reset_selection_and_adapter(cx);
643        }
644        cx.notify();
645    }
646
647    /// The text this view renders, which [`RangeHighlight`] ranges index.
648    ///
649    /// This is the string plain copy produces, as of the last parse that
650    /// landed; text set since then is not in it until its parse lands.
651    pub fn rendered_text(&self) -> RenderedText {
652        RenderedText::new(
653            self.entity_id,
654            self.committed_revision,
655            self.parsed_content.document.clone(),
656            self.rendered_index.clone(),
657        )
658    }
659
660    /// Replace the range highlights, whose ranges index the current rendered text.
661    ///
662    /// Compute ranges from the current [`Self::rendered_text`] and set them in
663    /// the same update. Search the new text again after its content changes.
664    /// Ranges of the Markdown source, such as [`Self::selected_source_range`]
665    /// returns, convert with [`RenderedText::range_for_source`].
666    /// A range crossing blocks paints in both, skipping their separator.
667    /// Text outside every block (separators, custom blocks, HTML blocks, and
668    /// inline objects) is left unpainted. Any invalid range rejects the set.
669    ///
670    /// Highlights follow unchanged text through updates. Text appended while
671    /// streaming keeps earlier highlights; after a table edit, cells in and
672    /// after the edited row lose theirs because cells are known by position.
673    /// Text backgrounds such as `<mark>` paint over a highlight; inline code
674    /// backgrounds paint under it.
675    pub fn set_range_highlights(
676        &mut self,
677        highlights: impl IntoIterator<Item = RangeHighlight>,
678        cx: &mut Context<Self>,
679    ) -> Result<(), RangeHighlightError> {
680        if self.format != TextViewFormat::Markdown {
681            return Err(RangeHighlightError::Unsupported);
682        }
683        let text = self.rendered_text();
684        self.range_highlights = RangeHighlightFrame::new(&text, highlights)?.map(Arc::new);
685        cx.notify();
686        Ok(())
687    }
688
689    /// Scroll the line `range` starts on into view, `range` indexing the
690    /// current rendered text, as with [`Self::set_range_highlights`].
691    ///
692    /// A [`Self::scrollable`] view scrolls itself. Otherwise the nearest
693    /// enclosing `wgpui::list` scrolls, as long as the row holding the view is
694    /// laid out, so scroll to that row first when it may be off screen. Any
695    /// other scroll container scrolls through
696    /// [`TextView::on_reveal`](crate::text::TextView::on_reveal). An empty
697    /// range reveals the line of its position; a range in text that belongs
698    /// to no block's text, such as a custom block's, scrolls its whole block
699    /// into a scrollable view.
700    ///
701    /// Only the latest reveal is carried out. It follows the content as
702    /// [range highlights](Self::set_range_highlights) do, and it is dropped
703    /// when its text changes, when the view clamps its lines, or when it
704    /// cannot be shown within a second, so it never scrolls long after it
705    /// was asked for. A whole block taller than the view, scrolled to from
706    /// below, shows its end.
707    ///
708    /// Revealing is best effort: `Ok(())` means the range is valid for the
709    /// current text and the request was taken, not that the view has
710    /// scrolled. A dropped request is not reported.
711    pub fn reveal_range(
712        &mut self,
713        range: Range<usize>,
714        cx: &mut Context<Self>,
715    ) -> Result<(), RangeHighlightError> {
716        if self.format != TextViewFormat::Markdown {
717            return Err(RangeHighlightError::Unsupported);
718        }
719        let text = self.rendered_text();
720        if text.is_empty() && range == (0..0) {
721            // Nothing to reveal in an empty view.
722            self.pending_reveal = None;
723            return Ok(());
724        }
725        let now = cx.background_executor().now();
726        self.pending_reveal = Some(
727            PendingReveal::new(&text, &range, now).ok_or(RangeHighlightError::InvalidRange(0))?,
728        );
729        cx.notify();
730        Ok(())
731    }
732
733    /// Remove all range highlights.
734    pub fn clear_range_highlights(&mut self, cx: &mut Context<Self>) {
735        if self.range_highlights.take().is_some() {
736            cx.notify();
737        }
738    }
739
740    /// Carry the range highlights over to `new`, the document the update of
741    /// `revision` parsed, before it replaces the current one.
742    ///
743    /// `append` is whether that update parsed only appended text onto the
744    /// document before it. Only when no update has replaced the text since
745    /// the current document was committed was that document the current one,
746    /// so only then do the blocks before its last stay unchanged.
747    fn reconcile_range_highlights(&mut self, new: &ParsedDocument, revision: usize, append: bool) {
748        let tail_only = append && self.full_update_revision <= self.committed_revision;
749        self.committed_revision = revision;
750        self.rendered_index = Arc::default();
751        if self.range_highlights.is_some() || self.pending_reveal.is_some() {
752            let remap = LeafRemap::new(&self.parsed_content.document, new, tail_only);
753            self.range_highlights = self
754                .range_highlights
755                .take()
756                .and_then(|highlights| highlights.remap(&remap))
757                .map(Arc::new);
758            self.pending_reveal = self
759                .pending_reveal
760                .take()
761                .and_then(|reveal| reveal.remap(&remap));
762        }
763    }
764
765    /// Tell the scrollable list which blocks an append replaced, before `new`,
766    /// the appended document, replaces the current one.
767    ///
768    /// An append parses only the current document's last block again, so the
769    /// blocks before it keep their spans and their measured heights. Without
770    /// this, `render_root` resets the list whenever the block count changes,
771    /// which scrolled a streaming view back to the top and measured every
772    /// block again on each new block. Only a grown block count is handled
773    /// here; anything else is left to that reset.
774    fn splice_appended_blocks(&self, new: &ParsedDocument) {
775        let old = &self.parsed_content.document.blocks;
776        let (old_count, new_count) = (old.len(), new.blocks.len());
777        if old_count == 0 || new_count <= old_count || self.list_state.item_count() != old_count {
778            return;
779        }
780
781        // The last block is always measured again: it was parsed again, and
782        // it is no longer the last one.
783        let unchanged = old
784            .iter()
785            .zip(new.blocks.iter())
786            .take(old_count - 1)
787            .take_while(|(old_block, new_block)| {
788                old_block
789                    .span()
790                    .is_some_and(|span| new_block.span() == Some(span))
791            })
792            .count();
793        // Keeps the replaced blocks' heights as hints and the scroll offset
794        // inside them, and has the next layout measure only the blocks that
795        // are not measured.
796        self.list_state.remeasure_items(unchanged..old_count);
797        self.list_state
798            .splice(old_count..old_count, new_count - old_count);
799    }
800
801    /// Save bounds and unselect if bounds changed.
802    pub(super) fn update_bounds(&mut self, bounds: Bounds<Pixels>, _cx: &mut App) {
803        self.bounds = bounds;
804    }
805
806    /// The index of the top-level block at `content_y`, in this view's content
807    /// coordinates (the same space the base selection endpoint stores its point in).
808    ///
809    /// Only laid-out blocks can be located, which is enough for a selection
810    /// endpoint: the user can only put one where they can see it. Returns
811    /// `None` for a view that is not virtualized, where every block paints and
812    /// the range is not needed.
813    pub(super) fn block_ix_at(&self, content_y: Pixels) -> Option<usize> {
814        if !self.scrollable {
815            return None;
816        }
817
818        let origin = self.bounds.origin.y + self.scroll_offset().y;
819        let count = self.list_state.item_count();
820        let mut ix = self.list_state.logical_scroll_top().item_ix;
821        while ix < count {
822            let bounds = self.list_state.bounds_for_item(ix)?;
823            if content_y < bounds.bottom() - origin {
824                return Some(ix);
825            }
826            ix += 1;
827        }
828
829        count.checked_sub(1)
830    }
831
832    #[doc(hidden)]
833    pub fn bounds(&self) -> Bounds<Pixels> {
834        self.bounds
835    }
836
837    #[doc(hidden)]
838    pub fn list_state(&self) -> &ListState {
839        &self.list_state
840    }
841
842    #[doc(hidden)]
843    pub fn is_selecting(&self) -> bool {
844        self.is_selecting
845    }
846
847    #[doc(hidden)]
848    pub fn focus_handle(&self) -> &FocusHandle {
849        &self.focus_handle
850    }
851
852    /// Whether this view has a view-local selection (select-all, multi-click, or override),
853    /// independent of the window-level selection.
854    pub(super) fn has_view_selection(&self) -> bool {
855        self.select_all
856            || self.multi_click_selection.is_some()
857            || self.selected_text_override.is_some()
858    }
859
860    pub(super) fn stop_auto_scroll(&mut self) {
861        self.auto_scroll.stop();
862    }
863
864    pub(super) fn reset_selection(&mut self) {
865        self.preserve_inline_selection = false;
866        self.multi_click_selection = None;
867        self.selected_text_override = None;
868        self.select_all = false;
869        self.is_selecting = false;
870        self.auto_scroll.stop();
871        // Clear the inline selection state synchronously, so offscreen
872        // (virtualized) views that won't repaint don't leak stale selection
873        // text into a new cross-view copy.
874        self.parsed_content.document.clear_selection();
875    }
876
877    fn reset_selection_and_adapter(&mut self, cx: &mut App) {
878        self.reset_selection();
879        self.selection_adapter.set_local_selection(false, cx);
880    }
881
882    /// Clear the current text selection.
883    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
884        self.reset_selection_and_adapter(cx);
885        cx.notify();
886    }
887
888    pub(super) fn scroll_offset(&self) -> Point<Pixels> {
889        if self.scrollable {
890            self.list_state.scroll_px_offset_for_scrollbar()
891        } else {
892            Point::default()
893        }
894    }
895
896    /// Select all rendered text in this view.
897    pub fn select_all(&mut self, cx: &mut Context<Self>) {
898        self.multi_click_selection = None;
899        self.selected_text_override = None;
900        self.select_all = true;
901        self.is_selecting = false;
902        self.auto_scroll.stop();
903        self.selection_adapter.set_local_selection(true, cx);
904        cx.notify();
905    }
906
907    /// Selects what a multi-click at `pos` selected, from the caret `start`
908    /// to the caret `end` in window coordinates. A drag from the click
909    /// extends it by the same unit.
910    pub(crate) fn set_multi_click_selection(
911        &mut self,
912        pos: Point<Pixels>,
913        kind: TextViewMultiClickKind,
914        selected_text: String,
915        (start, end): (Bounds<Pixels>, Bounds<Pixels>),
916        cx: &mut App,
917    ) {
918        self.preserve_inline_selection = false;
919        let scroll_offset = self.scroll_offset();
920        let pos = pos - self.bounds.origin - scroll_offset;
921        self.multi_click_selection = Some(TextViewMultiClickSelection {
922            pos,
923            kind,
924            line_bounds: None,
925        });
926        self.selected_text_override = Some(selected_text);
927        self.select_all = false;
928        self.is_selecting = false;
929        self.auto_scroll.stop();
930        self.selection_adapter.set_local_selection(true, cx);
931        let click_count = match kind {
932            TextViewMultiClickKind::Word => 2,
933            TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => 3,
934        };
935        self.selection_adapter
936            .hold_multi_click(start, end, click_count, cx);
937    }
938
939    /// Hands a multi-click selection over to the window selection, which a
940    /// drag from the click has taken beyond what the click selected.
941    pub(super) fn end_multi_click_selection(&mut self, cx: &mut App) {
942        if self.multi_click_selection.take().is_some() {
943            self.selected_text_override = None;
944            self.selection_adapter.set_local_selection(false, cx);
945        }
946    }
947
948    pub(crate) fn set_multi_click_line(&mut self, bounds: Bounds<Pixels>, cx: &mut App) {
949        self.set_multi_click_selection(
950            bounds.center(),
951            TextViewMultiClickKind::Line,
952            String::new(),
953            (
954                caret_line_box(bounds.origin, bounds.size.height),
955                caret_line_box(bounds.top_right(), bounds.size.height),
956            ),
957            cx,
958        );
959        self.selected_text_override = None;
960        let offset = self.bounds.origin + self.scroll_offset();
961        if let Some(selection) = self.multi_click_selection.as_mut() {
962            selection.line_bounds = Some(Bounds::new(bounds.origin - offset, bounds.size));
963        }
964    }
965
966    pub(super) fn set_auto_scroll(&mut self, delta: Option<Pixels>, cx: &mut Context<Self>) {
967        self.auto_scroll.set(delta, cx, |delta, state, cx| {
968            state.list_state.scroll_by(delta);
969            cx.notify();
970        });
971    }
972
973    /// Return the window selection (anchor, cursor) in window coordinates if
974    /// this view participates in it.
975    ///
976    /// Single-view fast path: when both endpoints are anchored inside one
977    /// TextView, only that view participates (identical to the previous
978    /// per-view behavior).
979    pub(crate) fn selection_points(&self, cx: &App) -> Option<(Point<Pixels>, Point<Pixels>)> {
980        if !self.selectable {
981            return None;
982        }
983        self.selection_adapter.selection_points(cx)
984    }
985
986    /// [`Self::selection_points`] for the text that paints now: a drag that
987    /// started in a table cell selects only in that cell. Call it only while
988    /// painting, so the cell the text is in is known.
989    pub(crate) fn painted_selection_points(
990        &self,
991        cx: &App,
992    ) -> Option<(Point<Pixels>, Point<Pixels>)> {
993        if !self.selectable {
994            return None;
995        }
996        self.selection_adapter.painted_selection_points(cx)
997    }
998
999    pub(crate) fn has_selection(&self, cx: &App) -> bool {
1000        self.has_view_selection() || self.selection_points(cx).is_some()
1001    }
1002
1003    pub(super) fn on_action_select_all(
1004        &mut self,
1005        _: &SelectAll,
1006        _: &mut Window,
1007        cx: &mut Context<Self>,
1008    ) {
1009        if !self.selectable {
1010            cx.propagate();
1011            return;
1012        }
1013
1014        self.select_all(cx);
1015    }
1016
1017    pub(crate) fn is_selectable(&self) -> bool {
1018        self.selectable
1019    }
1020
1021    pub(crate) fn is_all_selected(&self) -> bool {
1022        self.select_all
1023    }
1024
1025    pub(crate) fn multi_click_selection(&self) -> Option<TextViewMultiClickSelection> {
1026        let scroll_offset = self.scroll_offset();
1027        self.multi_click_selection.map(|selection| {
1028            let pos = selection.pos + scroll_offset + self.bounds.origin;
1029            let line_bounds = selection.line_bounds.map(|bounds| {
1030                Bounds::new(
1031                    bounds.origin + scroll_offset + self.bounds.origin,
1032                    bounds.size,
1033                )
1034            });
1035            TextViewMultiClickSelection {
1036                pos,
1037                line_bounds,
1038                ..selection
1039            }
1040        })
1041    }
1042}
1043
1044#[derive(Clone, Copy, Debug, PartialEq)]
1045pub(crate) struct TextViewMultiClickSelection {
1046    pub(crate) pos: Point<Pixels>,
1047    pub(crate) kind: TextViewMultiClickKind,
1048    pub(crate) line_bounds: Option<Bounds<Pixels>>,
1049}
1050
1051#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1052pub(crate) enum TextViewMultiClickKind {
1053    Word,
1054    Paragraph,
1055    Line,
1056}
1057
1058impl TextViewState {
1059    /// Starts a frame of the pending reveal: the line to hand to rendering,
1060    /// and the block a scrollable view has to scroll to first, because it is
1061    /// off screen or the reveal is of a whole block.
1062    fn reveal_frame(
1063        &mut self,
1064        now: Instant,
1065        window: &mut Window,
1066    ) -> (Option<RevealRequest>, Option<usize>) {
1067        if self.max_lines.is_some()
1068            || self
1069                .pending_reveal
1070                .as_ref()
1071                .is_some_and(|reveal| reveal.is_expired(now))
1072        {
1073            self.pending_reveal = None;
1074        }
1075        let Some(pending) = &self.pending_reveal else {
1076            return (None, None);
1077        };
1078
1079        let block_ix = pending.block_ix(&self.parsed_content.document);
1080        let block_off_screen = |ix: usize| {
1081            let viewport = self.list_state.viewport_bounds();
1082            self.list_state.bounds_for_item(ix).is_none_or(|item| {
1083                item.bottom() <= viewport.top() || item.top() >= viewport.bottom()
1084            })
1085        };
1086        let reveal_block = block_ix.filter(|ix| {
1087            self.scrollable
1088                && (pending.is_block() || !pending.was_laid_out())
1089                && block_off_screen(*ix)
1090        });
1091        let request = pending.request();
1092        if pending.is_block() {
1093            // A block has no line to wait for.
1094            self.pending_reveal = None;
1095        } else {
1096            window.request_animation_frame();
1097        }
1098        (request, reveal_block)
1099    }
1100}
1101
1102impl Render for TextViewState {
1103    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1104        let typography = (
1105            window.text_style(),
1106            window.rem_size(),
1107            window.scale_factor(),
1108        );
1109        let body_font_size = typography.0.font_size.to_pixels(typography.1);
1110        if self
1111            .layout_text_style
1112            .as_ref()
1113            .is_some_and(|previous| previous != &typography)
1114        {
1115            // ListState invalidates its cached rows for width changes, but does
1116            // not know that inherited typography or display scale changes
1117            // offscreen inline metrics. Retain logical selections as for resources.
1118            self.preserve_selection_for_reflow();
1119        }
1120        self.layout_text_style = Some(typography);
1121        let state = cx.entity();
1122        let stream_fade = self.stream_fade.frame(Instant::now(), cx.reduce_motion());
1123        if stream_fade.is_some() && self.fade_tick.is_none() {
1124            self.fade_tick = Some(cx.spawn(async move |this, cx| {
1125                cx.background_executor().timer(STREAM_FADE_TICK).await;
1126                _ = this.update(cx, |state, cx| {
1127                    state.fade_tick = None;
1128                    cx.notify();
1129                });
1130            }));
1131        }
1132        let (reveal, reveal_block) = self.reveal_frame(cx.background_executor().now(), window);
1133        // Built every frame, so everything in it is shared, not copied.
1134        let node_cx = NodeContext {
1135            offset: self.parsed_content.node_cx.offset,
1136            link_refs: self.parsed_content.node_cx.link_refs.clone(),
1137            style: self.text_view_style.clone(),
1138            code_block_actions: self.code_block_actions.clone(),
1139            code_block_highlighter: self.code_block_highlighter.clone(),
1140            table_actions: self.table_actions.clone(),
1141            link_click_handler: self.link_click_handler.clone(),
1142            image_source: self.image_source.clone(),
1143            markdown_extensions: self.markdown_extensions.clone(),
1144            stream_fade,
1145            range_highlights: self.range_highlights.clone(),
1146            reveal,
1147            body_font_size,
1148        };
1149
1150        let content = v_flex()
1151            .w_full()
1152            // Clamped content must keep its natural height: stretching it to
1153            // the capped box would hide the overflow the clamp has to measure.
1154            .when(self.max_lines.is_none(), |this| this.h_full())
1155            .map(|this| match &self.parsed_error {
1156                None => this.child(self.parsed_content.document.render_root(
1157                    if self.scrollable {
1158                        Some(self.list_state.clone())
1159                    } else {
1160                        None
1161                    },
1162                    &node_cx,
1163                    window,
1164                    cx,
1165                )),
1166                Some(err) => this.child(
1167                    v_flex()
1168                        .gap_1()
1169                        .child("Failed to parse content")
1170                        .child(err.to_string()),
1171                ),
1172            })
1173            .on_prepaint(move |bounds, window, cx| {
1174                let (
1175                    size_changed,
1176                    selection_involves_view,
1177                    has_selection_snapshot,
1178                    is_selecting,
1179                    compatible_layout_update,
1180                    preserve_width_selection,
1181                ) = {
1182                    let state = state.read(cx);
1183                    let has_selection_snapshot = state.selection_adapter.has_selection_snapshot(cx);
1184                    let preserve_width_selection = !state.is_selecting
1185                        && state.bounds().size.width != bounds.size.width
1186                        && (has_selection_snapshot || state.has_view_selection());
1187                    (
1188                        state.bounds().size != bounds.size,
1189                        state.selection_adapter.is_part_of_window_selection(cx),
1190                        has_selection_snapshot,
1191                        state.is_selecting,
1192                        // A measurement prepaint must not consume compatibility
1193                        // before the same entity's visible column prepaints.
1194                        state.compatible_layout_update
1195                            || preserve_width_selection
1196                            || state.preserve_inline_selection,
1197                        preserve_width_selection,
1198                    )
1199                };
1200                let mut revision_changed = false;
1201                state.update(cx, |state, cx| {
1202                    revision_changed = state
1203                        .selection_adapter
1204                        .update_layout_revision(state.selection_revision, state.is_selecting);
1205                    if preserve_width_selection {
1206                        // ListState already remeasures width changes. Arm logical
1207                        // retention before inline paint without invalidating rows again.
1208                        state.preserve_inline_selection = true;
1209                    }
1210                    state.update_bounds(bounds, cx);
1211                    state.compatible_layout_update = false;
1212                });
1213                if !is_selecting
1214                    && ((size_changed && selection_involves_view && !compatible_layout_update)
1215                        || (revision_changed && has_selection_snapshot))
1216                {
1217                    TextSelection::clear(window, cx);
1218                }
1219            });
1220        // After `render_root`, which resets the list when the block count
1221        // changed other than by an append, and with it the scroll position.
1222        if let Some(block_ix) = reveal_block {
1223            self.list_state.scroll_to_reveal_item(block_ix);
1224        }
1225        content
1226    }
1227}
1228
1229#[derive(Clone, PartialEq, Default)]
1230pub(crate) struct ParsedContent {
1231    pub(crate) document: ParsedDocument,
1232    pub(crate) node_cx: node::NodeContext,
1233}
1234
1235struct UpdateFuture {
1236    format: TextViewFormat,
1237    content: ParsedContent,
1238    rx: Pin<Box<Receiver<UpdateOptions>>>,
1239    tx_result: Sender<ParsedUpdate>,
1240}
1241
1242impl UpdateFuture {
1243    fn new(
1244        format: TextViewFormat,
1245        rx: Receiver<UpdateOptions>,
1246        tx_result: Sender<ParsedUpdate>,
1247    ) -> Self {
1248        Self {
1249            format,
1250            content: Default::default(),
1251            rx: Box::pin(rx),
1252            tx_result,
1253        }
1254    }
1255}
1256
1257impl Future for UpdateFuture {
1258    type Output = ();
1259
1260    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1261        loop {
1262            match self.rx.as_mut().poll_next(cx) {
1263                Poll::Ready(Some(mut options)) => {
1264                    let hit_coalesce_budget =
1265                        merge_pending_options(&mut options, self.rx.as_ref().get_ref());
1266
1267                    let res = parse_content(self.format, self.content.clone(), &options);
1268                    if let Ok(content) = &res {
1269                        self.content = content.clone();
1270                    }
1271                    _ = self.tx_result.try_send(ParsedUpdate {
1272                        revision: options.revision,
1273                        full_parse: !options.append,
1274                        selection_compatible: options.mode == ParseMode::Compatible,
1275                        baseline_ack: options.mode == ParseMode::BaselineAck,
1276                        result: res,
1277                    });
1278                    if hit_coalesce_budget {
1279                        cx.waker().wake_by_ref();
1280                        return Poll::Pending;
1281                    }
1282                    continue;
1283                }
1284                Poll::Ready(None) => return Poll::Ready(()),
1285                Poll::Pending => return Poll::Pending,
1286            }
1287        }
1288    }
1289}
1290
1291#[derive(Clone)]
1292struct UpdateOptions {
1293    revision: usize,
1294    pending_text: String,
1295    append: bool,
1296    mode: ParseMode,
1297    markdown_extensions: Arc<MarkdownExtensions>,
1298}
1299
1300impl UpdateOptions {
1301    fn merge(&mut self, next: UpdateOptions) {
1302        if next.append {
1303            self.pending_text.push_str(&next.pending_text);
1304            self.revision = next.revision;
1305            if self.mode != ParseMode::Replace {
1306                self.mode = ParseMode::Compatible;
1307            }
1308        } else {
1309            *self = next;
1310        }
1311    }
1312}
1313
1314struct ParsedUpdate {
1315    revision: usize,
1316    full_parse: bool,
1317    selection_compatible: bool,
1318    baseline_ack: bool,
1319    result: Result<ParsedContent, SharedString>,
1320}
1321
1322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1323enum ParseMode {
1324    BaselineAck,
1325    Replace,
1326    Compatible,
1327}
1328
1329fn merge_pending_options(options: &mut UpdateOptions, rx: &Receiver<UpdateOptions>) -> bool {
1330    let mut update_count = 1;
1331
1332    while update_count < MAX_COALESCED_UPDATES_PER_PARSE {
1333        match rx.try_recv() {
1334            Ok(next_options) => {
1335                options.merge(next_options);
1336                update_count += 1;
1337            }
1338            Err(_) => return false,
1339        }
1340    }
1341
1342    true
1343}
1344
1345fn parse_content(
1346    format: TextViewFormat,
1347    mut content: ParsedContent,
1348    options: &UpdateOptions,
1349) -> Result<ParsedContent, SharedString> {
1350    let mut node_cx = NodeContext {
1351        markdown_extensions: options.markdown_extensions.clone(),
1352        ..NodeContext::default()
1353    };
1354
1355    // Re-parse the last block together with the appended text, so a block the
1356    // new text continues (an unclosed list, a fenced code block) is not split
1357    // in two. A block without a span cannot be located in `source` — the HTML
1358    // parser never records spans — so it is left in place and only the
1359    // appended text is parsed, positioned at the end of the current source.
1360    let last_span = options
1361        .append
1362        .then(|| {
1363            content
1364                .document
1365                .blocks
1366                .last()
1367                .and_then(|block| block.span())
1368        })
1369        .flatten();
1370
1371    let mut source = String::new();
1372    if let Some(span) = last_span {
1373        Arc::make_mut(&mut content.document.blocks).pop();
1374        node_cx.offset = span.start;
1375        source.push_str(&content.document.source[span.start..]);
1376        source.push_str(&options.pending_text);
1377    } else {
1378        if options.append {
1379            node_cx.offset = content.document.source.len();
1380        }
1381        source.push_str(&options.pending_text);
1382    }
1383
1384    let new_document = match format {
1385        TextViewFormat::Markdown => format::markdown::parse(&source, &mut node_cx),
1386        TextViewFormat::Html => format::html::parse(&source, &mut node_cx),
1387    }?;
1388
1389    if options.append {
1390        content.document.source =
1391            format!("{}{}", content.document.source, options.pending_text).into();
1392        Arc::make_mut(&mut content.document.blocks)
1393            .extend(Arc::unwrap_or_clone(new_document.blocks));
1394    } else {
1395        content.document = new_document;
1396    }
1397
1398    Ok(content)
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403    use super::*;
1404    use crate::text::{
1405        MarkdownNode,
1406        node::{BlockNode, Span},
1407    };
1408    use wgpui::{Entity, TestAppContext};
1409
1410    mod stream_fade {
1411        use std::{cell::Cell, ops::Range, rc::Rc, time::Duration};
1412
1413        use wgpui::{Entity, TestAppContext};
1414
1415        use super::super::*;
1416        use crate::{motion::Easing, text::stream_fade::TextLeafKey};
1417
1418        /// Long enough that a debug test cannot outrun the fade before it
1419        /// samples the first frame.
1420        const FADE: Duration = Duration::from_secs(10);
1421
1422        fn fading_state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
1423            cx.update(crate::init);
1424            let state = cx.update(|cx| {
1425                cx.new(|cx| {
1426                    TextViewState::markdown(markdown, cx).motion(
1427                        TextViewMotion::default()
1428                            .with_stream_fade(FADE)
1429                            .with_stream_fade_easing(Easing::Linear),
1430                    )
1431                })
1432            });
1433            cx.run_until_parked();
1434            state
1435        }
1436
1437        /// The fade ranges of `key` sampled right now, or `None` when the
1438        /// state has nothing fading.
1439        fn fades(
1440            state: &Entity<TextViewState>,
1441            key: TextLeafKey,
1442            cx: &mut TestAppContext,
1443        ) -> Option<Vec<Range<usize>>> {
1444            state.update(cx, |state, _| {
1445                let frame = state.stream_fade.frame(Instant::now(), false)?;
1446                let fades = frame.fades(key)?;
1447                assert!(
1448                    fades.iter().all(|(_, fade_out)| *fade_out > 0.9),
1449                    "a fade sampled right after it starts is still transparent: {fades:?}"
1450                );
1451                Some(fades.iter().map(|(range, _)| range.clone()).collect())
1452            })
1453        }
1454
1455        #[wgpui::test]
1456        fn push_str_fades_only_the_appended_text(cx: &mut TestAppContext) {
1457            let state = fading_state("hello", cx);
1458            state.update(cx, |state, cx| state.push_str(" world", cx));
1459            cx.run_until_parked();
1460
1461            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1462
1463            state.update(cx, |state, _| {
1464                let later = Instant::now() + FADE + Duration::from_secs(1);
1465                assert!(state.stream_fade.frame(later, false).is_none());
1466                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1467            });
1468        }
1469
1470        #[wgpui::test]
1471        fn overtaken_parse_preserves_the_remaining_chunks_fade(cx: &mut TestAppContext) {
1472            let state = fading_state("hello", cx);
1473            let parsed = super::push_and_parse(&state, " one", cx);
1474            state.update(cx, |state, cx| {
1475                state.push_str(" two", cx);
1476                state.commit_parsed_update(parsed, cx);
1477            });
1478            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..9]));
1479
1480            cx.run_until_parked();
1481            assert_eq!(
1482                fades(&state, TextLeafKey::block(0), cx),
1483                Some(vec![5..9, 9..13])
1484            );
1485        }
1486
1487        #[wgpui::test]
1488        fn overtaken_parse_preserves_a_remaining_blocks_fade(cx: &mut TestAppContext) {
1489            let state = fading_state("hello", cx);
1490            let parsed = super::push_and_parse(&state, " one", cx);
1491            state.update(cx, |state, cx| {
1492                state.push_str("\n\nsecond", cx);
1493                state.commit_parsed_update(parsed, cx);
1494            });
1495            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..9]));
1496
1497            // A third chunk arrives while the second is still uncommitted.
1498            state.update(cx, |state, cx| state.push_str(" third", cx));
1499            cx.run_until_parked();
1500            let ranges = fades(&state, TextLeafKey::block(11), cx).expect("new paragraph fades");
1501            assert_eq!(
1502                ranges.into_iter().flatten().collect::<Vec<_>>(),
1503                (0..12).collect::<Vec<_>>()
1504            );
1505        }
1506
1507        #[wgpui::test]
1508        fn set_text_extending_the_text_fades_like_push_str(cx: &mut TestAppContext) {
1509            let state = fading_state("hello", cx);
1510            state.update(cx, |state, cx| state.set_text("hello world", cx));
1511            cx.run_until_parked();
1512
1513            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1514        }
1515
1516        #[wgpui::test]
1517        fn set_text_replacing_the_text_shows_it_at_once(cx: &mut TestAppContext) {
1518            let state = fading_state("hello", cx);
1519            state.update(cx, |state, cx| state.push_str(" world", cx));
1520            cx.run_until_parked();
1521            assert!(fades(&state, TextLeafKey::block(0), cx).is_some());
1522
1523            state.update(cx, |state, cx| state.set_text("other", cx));
1524            cx.run_until_parked();
1525
1526            assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1527        }
1528
1529        #[wgpui::test]
1530        fn completed_markup_refades_from_the_divergence(cx: &mut TestAppContext) {
1531            // The paragraph renders `text` (trailing space trimmed), then
1532            // `text **bo` literally.
1533            let state = fading_state("text ", cx);
1534            state.update(cx, |state, cx| state.push_str("**bo", cx));
1535            cx.run_until_parked();
1536            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![4..9]));
1537
1538            // `text **bold**` renders `text bold`: the space keeps its fade,
1539            // the glyphs from byte 5 on changed and fade again as one run.
1540            state.update(cx, |state, cx| state.push_str("ld**", cx));
1541            cx.run_until_parked();
1542            assert_eq!(
1543                fades(&state, TextLeafKey::block(0), cx),
1544                Some(vec![4..5, 5..9])
1545            );
1546        }
1547
1548        #[wgpui::test]
1549        fn without_stagger_an_update_fades_as_one_chunk(cx: &mut TestAppContext) {
1550            let state = fading_state("hello", cx);
1551            state.update(cx, |state, cx| state.push_str(" one two three", cx));
1552            cx.run_until_parked();
1553
1554            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..19]));
1555        }
1556
1557        #[wgpui::test]
1558        fn words_of_one_update_start_one_after_another(cx: &mut TestAppContext) {
1559            let stagger = Duration::from_millis(100);
1560            let state = fading_state("hello", cx);
1561            state.update(cx, |state, _| {
1562                state.set_motion(
1563                    TextViewMotion::default()
1564                        .with_stream_fade(FADE)
1565                        .with_stream_fade_stagger(stagger)
1566                        .with_stream_fade_easing(Easing::Linear),
1567                )
1568            });
1569            state.update(cx, |state, cx| state.push_str(" one two three", cx));
1570            cx.run_until_parked();
1571
1572            state.update(cx, |state, _| {
1573                let frame = state
1574                    .stream_fade
1575                    .frame(Instant::now() + stagger * 3, false)
1576                    .expect("words still fading");
1577                let fades = frame.fades(TextLeafKey::block(0)).expect("paragraph fades");
1578                let ranges: Vec<_> = fades.iter().map(|(range, _)| range.clone()).collect();
1579                assert_eq!(ranges, vec![5..10, 10..14, 14..19]);
1580                // A later word has faded less, so it is still more transparent.
1581                assert!(
1582                    fades[0].1 < fades[1].1 && fades[1].1 < fades[2].1,
1583                    "{fades:?}"
1584                );
1585            });
1586        }
1587
1588        #[wgpui::test]
1589        fn a_new_paragraph_fades_as_a_whole(cx: &mut TestAppContext) {
1590            let state = fading_state("first", cx);
1591            state.update(cx, |state, cx| state.push_str("\n\nsecond", cx));
1592            cx.run_until_parked();
1593
1594            assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1595            assert_eq!(fades(&state, TextLeafKey::block(7), cx), Some(vec![0..6]));
1596        }
1597
1598        #[wgpui::test]
1599        fn code_block_text_fades_by_block(cx: &mut TestAppContext) {
1600            let state = fading_state("```rs\nlet", cx);
1601            state.update(cx, |state, cx| state.push_str(" x", cx));
1602            cx.run_until_parked();
1603
1604            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![3..5]));
1605        }
1606
1607        #[wgpui::test]
1608        fn table_cells_fade_by_ordinal(cx: &mut TestAppContext) {
1609            let state = fading_state("| a | b |\n|---|---|\n| c | d", cx);
1610            state.update(cx, |state, cx| state.push_str("e |", cx));
1611            cx.run_until_parked();
1612
1613            assert_eq!(fades(&state, TextLeafKey::table_cell(0, 2), cx), None);
1614            assert_eq!(
1615                fades(&state, TextLeafKey::table_cell(0, 3), cx),
1616                Some(vec![1..2])
1617            );
1618        }
1619
1620        #[wgpui::test]
1621        fn zero_duration_records_nothing(cx: &mut TestAppContext) {
1622            cx.update(crate::init);
1623            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1624            cx.run_until_parked();
1625            state.update(cx, |state, cx| state.push_str(" world", cx));
1626            cx.run_until_parked();
1627
1628            state.update(cx, |state, _| {
1629                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1630            });
1631        }
1632
1633        #[wgpui::test]
1634        fn reduced_motion_drops_the_fade(cx: &mut TestAppContext) {
1635            let state = fading_state("hello", cx);
1636            state.update(cx, |state, cx| state.push_str(" world", cx));
1637            cx.run_until_parked();
1638
1639            state.update(cx, |state, _| {
1640                assert!(state.stream_fade.frame(Instant::now(), true).is_none());
1641                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1642            });
1643        }
1644
1645        #[wgpui::test]
1646        fn a_fade_repaints_on_a_timer_until_nothing_fades(cx: &mut TestAppContext) {
1647            struct FadeRoot(Entity<TextViewState>);
1648            impl Render for FadeRoot {
1649                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1650                    crate::text::TextView::new(&self.0)
1651                }
1652            }
1653
1654            let state = fading_state("hello", cx);
1655            let (_, cx) = cx.add_window_view(|_, _| FadeRoot(state.clone()));
1656            let notifies = Rc::new(Cell::new(0));
1657            let _subscription = cx.update(|_, cx| {
1658                let notifies = notifies.clone();
1659                cx.observe(&state, move |_, _| notifies.set(notifies.get() + 1))
1660            });
1661
1662            state.update(cx, |state, cx| state.push_str(" world", cx));
1663            cx.run_until_parked();
1664            cx.update(|window, cx| window.draw(cx).clear());
1665            let before = notifies.get();
1666
1667            cx.executor().advance_clock(STREAM_FADE_TICK / 2);
1668            cx.run_until_parked();
1669            assert_eq!(notifies.get(), before);
1670
1671            // Each tick repaints once, and that frame schedules the next tick.
1672            for tick in 1..=3 {
1673                cx.executor().advance_clock(STREAM_FADE_TICK);
1674                cx.run_until_parked();
1675                assert_eq!(notifies.get(), before + tick);
1676            }
1677
1678            // Replacing the text drops the fade, so the ticks stop.
1679            state.update(cx, |state, cx| state.set_text("other", cx));
1680            cx.run_until_parked();
1681            cx.executor().advance_clock(STREAM_FADE_TICK);
1682            cx.run_until_parked();
1683            let after = notifies.get();
1684            cx.executor().advance_clock(STREAM_FADE_TICK * 10);
1685            cx.run_until_parked();
1686            assert_eq!(notifies.get(), after);
1687            assert!(state.read_with(cx, |state, _| state.fade_tick.is_none()));
1688        }
1689    }
1690
1691    #[wgpui::test]
1692    fn small_full_replace_parses_before_background_executor_runs(cx: &mut TestAppContext) {
1693        cx.update(crate::init);
1694        let markdown = "# ready";
1695        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
1696
1697        state.read_with(cx, |state, _| {
1698            assert_eq!(state.source().as_str(), markdown);
1699            assert_eq!(state.parsed_content.document.blocks.len(), 1);
1700        });
1701    }
1702
1703    #[wgpui::test]
1704    fn large_markdown_and_html_full_replacements_wait_for_background_executor(
1705        cx: &mut TestAppContext,
1706    ) {
1707        cx.update(crate::init);
1708        let markdown = "# x\n\n".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
1709        let html = format!("<p>{}</p>", "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1));
1710        assert!(markdown.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1711        assert!(html.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1712
1713        let (markdown_state, html_state) = cx.update(|cx| {
1714            (
1715                cx.new(|cx| TextViewState::markdown(&markdown, cx)),
1716                cx.new(|cx| TextViewState::html(&html, cx)),
1717            )
1718        });
1719
1720        markdown_state.read_with(cx, |state, _| {
1721            assert_eq!(state.text.as_str(), markdown.as_str());
1722            assert!(state.source().as_str().is_empty());
1723            assert!(state.parsed_content.document.blocks.is_empty());
1724        });
1725        html_state.read_with(cx, |state, _| {
1726            assert_eq!(state.text.as_str(), html.as_str());
1727            assert!(state.source().as_str().is_empty());
1728            assert!(state.parsed_content.document.blocks.is_empty());
1729        });
1730
1731        cx.run_until_parked();
1732
1733        markdown_state.read_with(cx, |state, _| {
1734            assert_eq!(state.source().as_str(), markdown.as_str());
1735            assert!(!state.parsed_content.document.blocks.is_empty());
1736        });
1737        html_state.read_with(cx, |state, _| {
1738            assert_eq!(state.source().as_str(), html.as_str());
1739            assert!(!state.parsed_content.document.blocks.is_empty());
1740        });
1741    }
1742
1743    #[wgpui::test]
1744    fn inline_source_ranges_follow_streamed_tail_reparsing(cx: &mut TestAppContext) {
1745        cx.update(crate::init);
1746        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("中文 $a$\n\n尾 $x", cx)));
1747        state.update(cx, |state, cx| {
1748            let extensions = MarkdownExtensions::default().plugin(
1749                crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(|node, _| {
1750                    let markdown::mdast::Node::InlineMath(math) = node else {
1751                        return None;
1752                    };
1753                    Some(super::super::MarkdownNode::new("formula", ()).text(math.value.clone()))
1754                }),
1755            );
1756            state.set_markdown_extensions(Arc::new(extensions), cx);
1757        });
1758        cx.run_until_parked();
1759        state.update(cx, |state, cx| state.push_str("^2$ 后", cx));
1760        cx.run_until_parked();
1761        state.read_with(cx, |state, _| {
1762            let source = "中文 $a$\n\n尾 $x^2$ 后";
1763            assert_eq!(state.source().as_str(), source);
1764            let objects: Vec<_> = state
1765                .parsed_content
1766                .document
1767                .blocks
1768                .iter()
1769                .flat_map(|block| {
1770                    let super::super::node::BlockNode::Paragraph(paragraph) = block else {
1771                        panic!()
1772                    };
1773                    paragraph
1774                        .children
1775                        .iter()
1776                        .filter_map(|node| node.custom.as_ref())
1777                })
1778                .collect();
1779            assert_eq!(objects.len(), 2);
1780            for (object, markdown) in objects.iter().zip(["$a$", "$x^2$"]) {
1781                let start = source.find(markdown).unwrap();
1782                assert_eq!(object.source_range(), Some(start..start + markdown.len()));
1783                assert_eq!(object.as_markdown(), markdown);
1784            }
1785        });
1786    }
1787
1788    #[wgpui::test]
1789    fn async_full_replace_then_push_str_preserves_complete_source(cx: &mut TestAppContext) {
1790        cx.update(crate::init);
1791        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1792        cx.run_until_parked();
1793
1794        let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
1795        let expected = format!("{replacement} tail");
1796        state.update(cx, |state, cx| {
1797            state.set_text(&replacement, cx);
1798            state.push_str(" tail", cx);
1799        });
1800        cx.run_until_parked();
1801
1802        state.read_with(cx, |state, _| {
1803            assert_eq!(state.text.as_str(), expected.as_str());
1804            assert_eq!(state.source().as_str(), expected.as_str());
1805        });
1806    }
1807
1808    /// Push `chunk` and parse it the way the background parser would, without
1809    /// running the parser, returning the update it would send.
1810    fn push_and_parse(
1811        state: &Entity<TextViewState>,
1812        chunk: &str,
1813        cx: &mut TestAppContext,
1814    ) -> ParsedUpdate {
1815        let (revision, baseline) = state.update(cx, |state, cx| {
1816            state.push_str(chunk, cx);
1817            (state.revision, state.parsed_content.clone())
1818        });
1819        let options = UpdateOptions {
1820            revision,
1821            pending_text: chunk.to_string(),
1822            append: true,
1823            mode: ParseMode::Compatible,
1824            markdown_extensions: Arc::default(),
1825        };
1826        ParsedUpdate {
1827            revision,
1828            full_parse: false,
1829            selection_compatible: true,
1830            baseline_ack: false,
1831            result: parse_content(TextViewFormat::Markdown, baseline, &options),
1832        }
1833    }
1834
1835    #[wgpui::test]
1836    fn stream_commits_a_parse_that_a_newer_chunk_overtook(cx: &mut TestAppContext) {
1837        cx.update(crate::init);
1838        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("# Answer\n\n", cx)));
1839        cx.run_until_parked();
1840
1841        // Chunks arriving faster than they parse always push the next chunk
1842        // before the previous parse lands.
1843        let parsed = push_and_parse(&state, "Streaming", cx);
1844        state.update(cx, |state, cx| {
1845            state.push_str(" tokens", cx);
1846            state.commit_parsed_update(parsed, cx);
1847            assert_eq!(state.source().as_str(), "# Answer\n\nStreaming");
1848        });
1849
1850        cx.run_until_parked();
1851        state.read_with(cx, |state, _| {
1852            assert_eq!(state.source().as_str(), "# Answer\n\nStreaming tokens");
1853        });
1854    }
1855
1856    #[wgpui::test]
1857    fn a_parse_from_before_a_replacement_is_discarded(cx: &mut TestAppContext) {
1858        cx.update(crate::init);
1859        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1860        cx.run_until_parked();
1861
1862        let parsed = push_and_parse(&state, " text", cx);
1863        // Large enough to parse in the background, so the replacement is not
1864        // committed yet when the older parse lands.
1865        let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
1866        state.update(cx, |state, cx| {
1867            state.set_text(&replacement, cx);
1868            state.commit_parsed_update(parsed, cx);
1869            assert_eq!(state.source().as_str(), "old");
1870        });
1871
1872        cx.run_until_parked();
1873        state.read_with(cx, |state, _| {
1874            assert_eq!(state.source().as_str(), replacement.as_str());
1875        });
1876    }
1877
1878    #[wgpui::test]
1879    fn html_push_str_keeps_earlier_blocks(cx: &mut TestAppContext) {
1880        cx.update(crate::init);
1881        let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>first</p>", cx)));
1882        cx.run_until_parked();
1883
1884        state.update(cx, |state, cx| {
1885            state.push_str("<p>second</p>", cx);
1886        });
1887        cx.run_until_parked();
1888
1889        state.read_with(cx, |state, _| {
1890            assert_eq!(state.source().as_str(), "<p>first</p><p>second</p>");
1891            let text = state
1892                .parsed_content
1893                .document
1894                .blocks
1895                .iter()
1896                .map(|block| block.text())
1897                .collect::<String>();
1898            assert!(text.contains("first"), "lost the first block: {text:?}");
1899            assert!(text.contains("second"), "lost the appended block: {text:?}");
1900        });
1901    }
1902
1903    #[wgpui::test]
1904    fn element_text_of_the_same_string_is_not_compared_again(cx: &mut TestAppContext) {
1905        cx.update(crate::init);
1906        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
1907        let revision = |cx: &mut TestAppContext| state.read_with(cx, |state, _| state.revision);
1908        let text = SharedString::from("hello");
1909
1910        state.update(cx, |state, cx| state.set_element_text(&text, cx));
1911        let parsed = revision(cx);
1912        assert!(parsed > 0);
1913
1914        // The same allocation again, and equal bytes in another allocation,
1915        // both leave the parsed text alone.
1916        state.update(cx, |state, cx| state.set_element_text(&text, cx));
1917        assert_eq!(revision(cx), parsed);
1918        let equal = SharedString::from("hello".to_string());
1919        state.update(cx, |state, cx| state.set_element_text(&equal, cx));
1920        assert_eq!(revision(cx), parsed);
1921
1922        // Once the state's text moved on, the element's string is set again.
1923        state.update(cx, |state, cx| {
1924            state.push_str(" world", cx);
1925            state.set_element_text(&equal, cx);
1926        });
1927        state.read_with(cx, |state, _| assert_eq!(state.text.as_str(), "hello"));
1928    }
1929
1930    #[wgpui::test]
1931    fn set_text_then_push_str_appends_to_replaced_content(cx: &mut TestAppContext) {
1932        cx.update(crate::init);
1933        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1934        cx.run_until_parked();
1935
1936        state.update(cx, |state, cx| {
1937            state.set_text("", cx);
1938            state.push_str("new", cx);
1939            state.push_str(" text", cx);
1940        });
1941        cx.run_until_parked();
1942
1943        state.read_with(cx, |state, _| {
1944            assert_eq!(state.text.as_str(), "new text");
1945            assert_eq!(state.source().as_str(), "new text");
1946        });
1947
1948        state.update(cx, |state, cx| {
1949            state.set_text("", cx);
1950        });
1951        cx.run_until_parked();
1952
1953        state.read_with(cx, |state, _| {
1954            assert_eq!(state.text.as_str(), "");
1955            assert_eq!(state.source().as_str(), "");
1956        });
1957    }
1958
1959    #[wgpui::test]
1960    fn full_parse_coalesced_with_append_preserves_new_select_all(cx: &mut TestAppContext) {
1961        cx.update(crate::init);
1962        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1963        cx.run_until_parked();
1964
1965        state.update(cx, |state, cx| {
1966            state.set_text("new", cx);
1967            state.push_str(" text", cx);
1968            state.select_all(cx);
1969        });
1970        cx.run_until_parked();
1971
1972        state.read_with(cx, |state, _| {
1973            assert!(state.select_all);
1974            assert_eq!(state.selected_text().trim(), "new text");
1975        });
1976    }
1977
1978    fn parsed_blocks(
1979        state: &Entity<TextViewState>,
1980        cx: &mut TestAppContext,
1981    ) -> Vec<(String, Option<Span>)> {
1982        state.read_with(cx, |state, _| {
1983            state
1984                .parsed_content
1985                .document
1986                .blocks
1987                .iter()
1988                .map(|block| (block.text(), block.span()))
1989                .collect()
1990        })
1991    }
1992
1993    #[wgpui::test]
1994    fn set_text_extending_markdown_appends_and_keeps_selection(cx: &mut TestAppContext) {
1995        cx.update(crate::init);
1996        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1997        cx.run_until_parked();
1998        let revisions =
1999            |state: &TextViewState| (state.selection_revision, state.full_update_revision);
2000        let initial = state.read_with(cx, |state, _| revisions(state));
2001
2002        state.update(cx, |state, cx| state.set_text("hello world", cx));
2003        cx.run_until_parked();
2004        state.read_with(cx, |state, _| {
2005            assert_eq!(state.source().as_str(), "hello world");
2006            assert_eq!(revisions(state), initial);
2007        });
2008
2009        state.update(cx, |state, cx| state.set_text("hello", cx));
2010        cx.run_until_parked();
2011        state.read_with(cx, |state, _| {
2012            assert_eq!(state.source().as_str(), "hello");
2013            assert_ne!(state.selection_revision, initial.0);
2014            assert_ne!(state.full_update_revision, initial.1);
2015        });
2016    }
2017
2018    #[wgpui::test]
2019    fn set_text_streaming_markdown_matches_a_full_parse(cx: &mut TestAppContext) {
2020        cx.update(crate::init);
2021        let streamed = cx.update(|cx| cx.new(|cx| TextViewState::markdown("# Title", cx)));
2022        cx.run_until_parked();
2023
2024        // Chunks continue a heading, a paragraph, an inline code span, a list
2025        // and a fenced code block, and the text grows past the synchronous
2026        // parse limit.
2027        let filler = "word ".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
2028        let chunks = [
2029            "\n\nfirst para",
2030            "graph with `co",
2031            "de`\n\n- one\n",
2032            "- two\n\n```rust\nfn main() {",
2033            "}\n```\n\n",
2034            filler.as_str(),
2035            "\n\nlast",
2036        ];
2037        let full_update_revision = streamed.read_with(cx, |state, _| state.full_update_revision);
2038        let mut text = "# Title".to_string();
2039        for chunk in chunks {
2040            text.push_str(chunk);
2041            streamed.update(cx, |state, cx| state.set_text(&text, cx));
2042            cx.run_until_parked();
2043        }
2044        assert_eq!(
2045            streamed.read_with(cx, |state, _| state.full_update_revision),
2046            full_update_revision
2047        );
2048
2049        let parsed = cx.update(|cx| cx.new(|cx| TextViewState::markdown(&text, cx)));
2050        cx.run_until_parked();
2051
2052        assert_eq!(
2053            streamed.read_with(cx, |state, _| state.source()),
2054            parsed.read_with(cx, |state, _| state.source())
2055        );
2056        assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
2057    }
2058
2059    #[wgpui::test]
2060    fn set_text_extending_html_parses_it_again(cx: &mut TestAppContext) {
2061        cx.update(crate::init);
2062        let streamed = cx.update(|cx| cx.new(|cx| TextViewState::html("<ul><li>a</li>", cx)));
2063        cx.run_until_parked();
2064
2065        let text = "<ul><li>a</li><li>b</li></ul>";
2066        streamed.update(cx, |state, cx| state.set_text(text, cx));
2067        cx.run_until_parked();
2068        assert_ne!(
2069            streamed.read_with(cx, |state, _| state.full_update_revision),
2070            0
2071        );
2072
2073        let parsed = cx.update(|cx| cx.new(|cx| TextViewState::html(text, cx)));
2074        cx.run_until_parked();
2075        assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
2076    }
2077
2078    #[wgpui::test]
2079    fn set_text_extending_after_a_parse_error_parses_it_again(cx: &mut TestAppContext) {
2080        cx.update(crate::init);
2081        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
2082        cx.run_until_parked();
2083
2084        let full_update_revision = state.read_with(cx, |state, _| state.full_update_revision);
2085
2086        state.update(cx, |state, cx| {
2087            state.parsed_error = Some("failed".into());
2088            state.set_text("hello world", cx);
2089        });
2090        cx.run_until_parked();
2091
2092        state.read_with(cx, |state, _| {
2093            assert!(state.parsed_error.is_none());
2094            assert_ne!(state.full_update_revision, full_update_revision);
2095            assert_eq!(state.source().as_str(), "hello world");
2096        });
2097    }
2098
2099    #[test]
2100    fn update_options_merge_keeps_latest_full_text() {
2101        let mut options = UpdateOptions {
2102            revision: 1,
2103            pending_text: "old".to_string(),
2104            append: true,
2105            mode: ParseMode::Compatible,
2106            markdown_extensions: Arc::default(),
2107        };
2108
2109        options.merge(UpdateOptions {
2110            revision: 2,
2111            pending_text: "new".to_string(),
2112            append: false,
2113            mode: ParseMode::BaselineAck,
2114            markdown_extensions: Arc::default(),
2115        });
2116        options.merge(UpdateOptions {
2117            revision: 3,
2118            pending_text: " text".to_string(),
2119            append: true,
2120            mode: ParseMode::Compatible,
2121            markdown_extensions: Arc::default(),
2122        });
2123
2124        assert_eq!(options.revision, 3);
2125        assert_eq!(options.pending_text, "new text");
2126        assert!(!options.append);
2127    }
2128
2129    #[test]
2130    fn append_merged_into_async_replace_remains_a_replacement() {
2131        let mut options = UpdateOptions {
2132            revision: 1,
2133            pending_text: "new".to_string(),
2134            append: false,
2135            mode: ParseMode::Replace,
2136            markdown_extensions: Arc::default(),
2137        };
2138
2139        options.merge(UpdateOptions {
2140            revision: 2,
2141            pending_text: " text".to_string(),
2142            append: true,
2143            mode: ParseMode::Compatible,
2144            markdown_extensions: Arc::default(),
2145        });
2146
2147        assert_eq!(options.revision, 2);
2148        assert_eq!(options.pending_text, "new text");
2149        assert!(!options.append);
2150        assert_eq!(options.mode, ParseMode::Replace);
2151    }
2152
2153    #[test]
2154    fn update_future_yields_before_coalescing_all_queued_updates() {
2155        let (tx, rx) = unbounded::<UpdateOptions>();
2156        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
2157        let total_updates = 128;
2158
2159        for revision in 1..=total_updates {
2160            tx.try_send(UpdateOptions {
2161                revision,
2162                pending_text: format!("{revision}\n"),
2163                append: revision != 1,
2164                mode: if revision == 1 {
2165                    ParseMode::BaselineAck
2166                } else {
2167                    ParseMode::Compatible
2168                },
2169                markdown_extensions: Arc::default(),
2170            })
2171            .unwrap();
2172        }
2173
2174        let mut future = Box::pin(UpdateFuture::new(TextViewFormat::Markdown, rx, tx_result));
2175        let waker = futures::task::noop_waker();
2176        let mut task_cx = std::task::Context::from_waker(&waker);
2177
2178        assert!(matches!(
2179            std::future::Future::poll(future.as_mut(), &mut task_cx),
2180            Poll::Pending
2181        ));
2182        let parsed_update = rx_result.try_recv().expect("parse result");
2183
2184        assert!(
2185            parsed_update.revision < total_updates,
2186            "single poll coalesced every queued update through revision {}",
2187            parsed_update.revision
2188        );
2189
2190        assert!(matches!(
2191            std::future::Future::poll(future.as_mut(), &mut task_cx),
2192            Poll::Pending
2193        ));
2194        let parsed_update = rx_result.try_recv().expect("next parse result");
2195        assert_eq!(parsed_update.revision, total_updates);
2196    }
2197
2198    #[wgpui::test]
2199    fn select_all_returns_rendered_text(cx: &mut TestAppContext) {
2200        cx.update(crate::init);
2201        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("**quick** value", cx)));
2202        cx.run_until_parked();
2203
2204        state.update(cx, |state, cx| {
2205            state.select_all(cx);
2206        });
2207
2208        state.read_with(cx, |state, _| {
2209            assert!(state.has_view_selection());
2210            assert_eq!(state.selected_text().trim(), "quick value");
2211        });
2212
2213        state.update(cx, |state, cx| {
2214            state.clear_selection(cx);
2215        });
2216
2217        state.read_with(cx, |state, _| {
2218            assert!(!state.has_view_selection());
2219            assert_eq!(state.selected_text(), "");
2220        });
2221    }
2222
2223    #[wgpui::test]
2224    fn select_all_in_source_format_returns_source(cx: &mut TestAppContext) {
2225        cx.update(crate::init);
2226        let markdown = "**quick** value";
2227        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2228        cx.run_until_parked();
2229
2230        state.update(cx, |state, cx| state.select_all(cx));
2231
2232        // The default (plain) mode strips the markup.
2233        state.read_with(cx, |state, _| {
2234            assert_eq!(state.selected_text().trim(), "quick value");
2235        });
2236
2237        state.update(cx, |state, cx| {
2238            state.set_selection_format(SelectionFormat::Source, cx)
2239        });
2240
2241        // Source mode yields the whole source verbatim.
2242        state.read_with(cx, |state, _| {
2243            assert_eq!(state.selected_text().trim(), markdown);
2244        });
2245    }
2246
2247    #[wgpui::test]
2248    fn selected_source_range_returns_full_markdown_source_for_select_all(cx: &mut TestAppContext) {
2249        cx.update(crate::init);
2250        let markdown = "**quick** value";
2251        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2252        cx.run_until_parked();
2253
2254        state.update(cx, |state, cx| state.select_all(cx));
2255
2256        state.read_with(cx, |state, _| {
2257            assert_eq!(state.selected_source_range(), Some(0..markdown.len()));
2258        });
2259    }
2260
2261    #[wgpui::test]
2262    fn selected_source_range_returns_none_for_html(cx: &mut TestAppContext) {
2263        cx.update(crate::init);
2264        let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<b>quick</b>", cx)));
2265        cx.run_until_parked();
2266
2267        state.update(cx, |state, cx| state.select_all(cx));
2268
2269        state.read_with(cx, |state, _| {
2270            assert_eq!(state.selected_source_range(), None);
2271        });
2272    }
2273
2274    #[test]
2275    fn selected_source_range_keeps_global_offsets_after_incremental_tail_parse() {
2276        let options = UpdateOptions {
2277            revision: 1,
2278            pending_text: "first\n\nsecond".to_string(),
2279            append: false,
2280            mode: ParseMode::Replace,
2281            markdown_extensions: Arc::default(),
2282        };
2283        let content = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2284            .expect("initial parse");
2285        let content = parse_content(
2286            TextViewFormat::Markdown,
2287            content,
2288            &UpdateOptions {
2289                revision: 2,
2290                pending_text: "\n\n**écho**".to_string(),
2291                append: true,
2292                mode: ParseMode::Compatible,
2293                markdown_extensions: Arc::default(),
2294            },
2295        )
2296        .expect("incremental parse");
2297        let BlockNode::Paragraph(paragraph) = &content.document.blocks[2] else {
2298            panic!("expected appended paragraph");
2299        };
2300        let mut state = paragraph.state.lock().unwrap();
2301        state.set_text(paragraph.text().into());
2302        state.selection = Some((0.."écho".len()).into());
2303        drop(state);
2304
2305        assert_eq!(content.document.selected_source_range(), Some(17..22));
2306    }
2307
2308    #[test]
2309    fn streamed_ordered_list_continuation_preserves_start() {
2310        let initial = parse_content(
2311            TextViewFormat::Markdown,
2312            ParsedContent::default(),
2313            &UpdateOptions {
2314                revision: 1,
2315                pending_text: "3. three".to_string(),
2316                append: false,
2317                mode: ParseMode::Replace,
2318                markdown_extensions: Arc::default(),
2319            },
2320        )
2321        .expect("initial list parse");
2322        let continued = parse_content(
2323            TextViewFormat::Markdown,
2324            initial,
2325            &UpdateOptions {
2326                revision: 2,
2327                pending_text: "\n4. four".to_string(),
2328                append: true,
2329                mode: ParseMode::Compatible,
2330                markdown_extensions: Arc::default(),
2331            },
2332        )
2333        .expect("streamed list continuation parse");
2334
2335        let BlockNode::List {
2336            start, children, ..
2337        } = &continued.document.blocks[0]
2338        else {
2339            panic!("expected streamed ordered list");
2340        };
2341        assert_eq!(*start, Some(3));
2342        assert_eq!(children.len(), 2);
2343    }
2344
2345    #[wgpui::test]
2346    fn parser_revision_reparses_same_name_inline_configuration(cx: &mut TestAppContext) {
2347        cx.update(crate::init);
2348        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("@member", cx)));
2349        for (revision, label) in [(1, "Alice"), (2, "Bob")] {
2350            let extensions = MarkdownExtensions::default()
2351                .parser_revision(revision)
2352                .plugin(
2353                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2354                        move |node, _| {
2355                            matches!(node, markdown::mdast::Node::Text(_))
2356                                .then(|| MarkdownNode::new("mention", label).text(label))
2357                        },
2358                    ),
2359                );
2360            state.update(cx, |state, cx| {
2361                state.set_markdown_extensions(Arc::new(extensions), cx)
2362            });
2363            cx.run_until_parked();
2364            state.read_with(cx, |state, _| {
2365                let node::BlockNode::Paragraph(paragraph) =
2366                    &state.parsed_content.document.blocks[0]
2367                else {
2368                    panic!()
2369                };
2370                assert_eq!(
2371                    paragraph.children[0].custom.as_ref().unwrap().as_text(),
2372                    label
2373                );
2374            });
2375        }
2376    }
2377
2378    #[wgpui::test]
2379    fn set_markdown_extensions_reparses_existing_text(cx: &mut TestAppContext) {
2380        cx.update(crate::init);
2381        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("$TSLA.US", cx)));
2382        cx.run_until_parked();
2383
2384        let extensions = MarkdownExtensions::default().block_parser(|node, cx| {
2385            let markdown::mdast::Node::Paragraph(paragraph) = node else {
2386                return None;
2387            };
2388            let [markdown::mdast::Node::Text(text)] = paragraph.children.as_slice() else {
2389                return None;
2390            };
2391            let symbol = text.value.strip_prefix('$')?.to_string();
2392            let node_text = format!("${symbol}");
2393
2394            Some(
2395                MarkdownNode::new("ticker", symbol)
2396                    .text(node_text)
2397                    .markdown(cx.node_source(node).unwrap_or_default().to_owned()),
2398            )
2399        });
2400
2401        state.update(cx, |state, cx| {
2402            state.set_markdown_extensions(Arc::new(extensions), cx);
2403        });
2404        cx.run_until_parked();
2405
2406        state.read_with(cx, |state, _| {
2407            let node::BlockNode::Custom { node, .. } = &state.parsed_content.document.blocks[0]
2408            else {
2409                panic!("expected custom markdown node");
2410            };
2411            assert_eq!(node.name(), "ticker");
2412            assert_eq!(node.data::<String>().map(String::as_str), Some("TSLA.US"));
2413        });
2414    }
2415
2416    mod range_highlights {
2417        use std::ops::Range;
2418
2419        use wgpui::{Entity, TestAppContext};
2420
2421        use super::super::*;
2422        use crate::text::stream_fade::TextLeafKey;
2423
2424        fn state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
2425            cx.update(crate::init);
2426            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2427            cx.run_until_parked();
2428            state
2429        }
2430
2431        fn highlight(range: Range<usize>) -> RangeHighlight {
2432            RangeHighlight::new(range, wgpui::hsla(0.15, 1., 0.5, 0.4))
2433        }
2434
2435        /// Highlights `ranges` of the current rendered text.
2436        fn set(
2437            state: &Entity<TextViewState>,
2438            ranges: impl IntoIterator<Item = Range<usize>>,
2439            cx: &mut TestAppContext,
2440        ) -> Result<(), RangeHighlightError> {
2441            state.update(cx, |state, cx| {
2442                state.set_range_highlights(ranges.into_iter().map(highlight), cx)
2443            })
2444        }
2445
2446        /// The ranges leaf `key` paints, in its own byte space.
2447        fn painted(
2448            state: &Entity<TextViewState>,
2449            key: TextLeafKey,
2450            cx: &mut TestAppContext,
2451        ) -> Vec<Range<usize>> {
2452            state.read_with(cx, |state, _| {
2453                state.range_highlights.as_ref().map_or(Vec::new(), |frame| {
2454                    frame
2455                        .backgrounds(key)
2456                        .iter()
2457                        .map(|(range, _)| range.clone())
2458                        .collect()
2459                })
2460            })
2461        }
2462
2463        fn has_highlights(state: &Entity<TextViewState>, cx: &mut TestAppContext) -> bool {
2464            state.read_with(cx, |state, _| state.range_highlights.is_some())
2465        }
2466
2467        #[wgpui::test]
2468        fn rendered_text_is_the_plain_copy_text(cx: &mut TestAppContext) {
2469            let state = state(
2470                "# Title\n\nhello **world** \\*\n\n- item\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```",
2471                cx,
2472            );
2473            state.read_with(cx, |state, _| {
2474                assert_eq!(
2475                    state.rendered_text().as_str(),
2476                    "Title\nhello world *\nitem\na b\nc d\n\nlet x\n"
2477                );
2478            });
2479        }
2480
2481        #[wgpui::test]
2482        fn a_match_across_marks_paints_in_its_paragraph(cx: &mut TestAppContext) {
2483            let state = state("hello **world**", cx);
2484            set(&state, [0.."hello world".len()], cx).unwrap();
2485            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..11]);
2486        }
2487
2488        #[wgpui::test]
2489        fn repeated_text_maps_to_the_occurrence_addressed(cx: &mut TestAppContext) {
2490            let state = state("foo\n\nfoo", cx);
2491            let second = state.read_with(cx, |state, _| {
2492                state.rendered_text().as_str().rfind("foo").unwrap()
2493            });
2494            set(&state, [second..second + 3], cx).unwrap();
2495            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2496            assert_eq!(painted(&state, TextLeafKey::block(5), cx), [0..3]);
2497        }
2498
2499        #[wgpui::test]
2500        fn a_range_across_blocks_skips_the_separator(cx: &mut TestAppContext) {
2501            let state = state("ab\n\ncd", cx);
2502            // "ab\ncd\n": 1..4 is "b\nc".
2503            set(&state, [1..4], cx).unwrap();
2504            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [1..2]);
2505            assert_eq!(painted(&state, TextLeafKey::block(4), cx), [0..1]);
2506        }
2507
2508        #[wgpui::test]
2509        fn table_cells_and_code_blocks_are_leaves(cx: &mut TestAppContext) {
2510            let state = state("| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```", cx);
2511            // "a b\nc d\n\nlet x\n"
2512            set(&state, [0..3, 6..7, 9..12], cx).unwrap();
2513            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2514            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 1), cx), [0..1]);
2515            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 3), cx), [0..1]);
2516            let code_start = "| a | b |\n|---|---|\n| c | d |\n\n".len();
2517            assert_eq!(painted(&state, TextLeafKey::block(code_start), cx), [0..3]);
2518        }
2519
2520        #[wgpui::test]
2521        fn invalid_ranges_reject_the_whole_set(cx: &mut TestAppContext) {
2522            let state = state("中文\n\nab", cx);
2523            // "中文\nab\n"
2524            set(&state, [0.."中".len()], cx).unwrap();
2525            let invalid = [Range { start: 6, end: 3 }, 0..1, 0..100];
2526            for range in invalid {
2527                assert_eq!(
2528                    set(&state, [0..3, range.clone()], cx),
2529                    Err(RangeHighlightError::InvalidRange(1)),
2530                    "{range:?}"
2531                );
2532            }
2533            // The rejected sets left the earlier highlight in place.
2534            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2535        }
2536
2537        #[wgpui::test]
2538        fn text_outside_every_block_is_left_unpainted(cx: &mut TestAppContext) {
2539            let source = "foo one\n\n<div>foo two</div>\n\n| foo | x |\n|---|---|\n\nfoo three";
2540            let state = state(source, cx);
2541            let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
2542            // Every "foo" and " ", an empty range, and the separator after the
2543            // first block: the HTML block's text and the separators are not
2544            // any block's text, so they paint nothing, but nothing fails.
2545            let ranges = text
2546                .match_indices("foo")
2547                .chain(text.match_indices(' '))
2548                .map(|(start, found)| start..start + found.len())
2549                .chain([3..3, 7..8])
2550                .collect::<Vec<_>>();
2551            set(&state, ranges, cx).unwrap();
2552            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3, 3..4]);
2553            let table = source.find("| foo").unwrap();
2554            assert_eq!(
2555                painted(&state, TextLeafKey::table_cell(table, 0), cx),
2556                [0..3]
2557            );
2558            let last = source.find("foo three").unwrap();
2559            assert_eq!(painted(&state, TextLeafKey::block(last), cx), [0..3, 3..4]);
2560        }
2561
2562        #[wgpui::test]
2563        fn a_later_highlight_paints_over_an_earlier_one(cx: &mut TestAppContext) {
2564            let state = state("abcdef", cx);
2565            set(&state, [0..6, 2..3], cx).unwrap();
2566            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..6, 2..3]);
2567        }
2568
2569        #[wgpui::test]
2570        fn html_text_is_unsupported(cx: &mut TestAppContext) {
2571            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
2572            cx.run_until_parked();
2573            html.update(cx, |html, cx| {
2574                assert_eq!(
2575                    html.set_range_highlights([highlight(0..3)], cx),
2576                    Err(RangeHighlightError::Unsupported)
2577                );
2578            });
2579        }
2580
2581        #[wgpui::test]
2582        fn inline_objects_are_skipped(cx: &mut TestAppContext) {
2583            let state = state("x $a$ y", cx);
2584            state.update(cx, |state, cx| {
2585                let extensions = MarkdownExtensions::default().plugin(
2586                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2587                        |node, _| {
2588                            let markdown::mdast::Node::InlineMath(math) = node else {
2589                                return None;
2590                            };
2591                            Some(
2592                                crate::text::MarkdownNode::new("formula", ())
2593                                    .text(math.value.clone()),
2594                            )
2595                        },
2596                    ),
2597                );
2598                state.set_markdown_extensions(Arc::new(extensions), cx);
2599            });
2600            cx.run_until_parked();
2601            // "x a y\n", where "a" is the formula.
2602            set(&state, [2..3], cx).unwrap();
2603            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2604            set(&state, [0..5], cx).unwrap();
2605            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..2, 3..5]);
2606        }
2607
2608        #[wgpui::test]
2609        fn push_str_keeps_earlier_blocks_and_clips_the_changed_tail(cx: &mut TestAppContext) {
2610            let state = state("first\n\na **b", cx);
2611            // "first\na **b\n"
2612            set(&state, [0..5, 6..11], cx).unwrap();
2613
2614            // Closing the emphasis renders the tail as "a bc".
2615            state.update(cx, |state, cx| state.push_str("c**", cx));
2616            cx.run_until_parked();
2617
2618            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2619            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..2]);
2620        }
2621
2622        #[wgpui::test]
2623        fn push_str_keeps_a_block_whose_text_is_unchanged(cx: &mut TestAppContext) {
2624            let state = state("first\n\nsecond", cx);
2625            set(&state, [6..12], cx).unwrap();
2626            // A setext underline turns the paragraph into a heading at the
2627            // same source start, rendering the same text.
2628            state.update(cx, |state, cx| state.push_str("\n===", cx));
2629            cx.run_until_parked();
2630            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..6]);
2631        }
2632
2633        #[wgpui::test]
2634        fn push_str_drops_highlights_of_a_leaf_that_is_gone(cx: &mut TestAppContext) {
2635            let state = state("first\n\n| a |", cx);
2636            set(&state, [0..5, 6..11], cx).unwrap();
2637            // A delimiter row turns the paragraph into a table, whose text
2638            // lives in cells instead.
2639            state.update(cx, |state, cx| state.push_str("\n|---|", cx));
2640            cx.run_until_parked();
2641            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2642            assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2643            assert!(painted(&state, TextLeafKey::table_cell(7, 0), cx).is_empty());
2644        }
2645
2646        #[wgpui::test]
2647        fn replacing_text_drops_highlights_only_where_it_changed(cx: &mut TestAppContext) {
2648            let state = state("first\n\nsecond", cx);
2649            set(&state, [0..5, 6..12], cx).unwrap();
2650            state.update(cx, |state, cx| state.set_text("first\n\nchanged", cx));
2651            cx.run_until_parked();
2652            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2653            assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2654
2655            let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2656            state.update(cx, |state, cx| state.set_text(&large, cx));
2657            cx.run_until_parked();
2658            assert!(!has_highlights(&state, cx));
2659        }
2660
2661        #[wgpui::test]
2662        fn a_highlight_follows_its_block_past_an_earlier_edit(cx: &mut TestAppContext) {
2663            let state = state("foo\n\nbar\n\nbar", cx);
2664            // "foo\nbar\nbar\n": the first "bar", in the block at source 5.
2665            set(&state, [4..7], cx).unwrap();
2666            // Deleting "foo" moves that "bar" to 0, and the second one to 5.
2667            state.update(cx, |state, cx| state.set_text("bar\n\nbar", cx));
2668            cx.run_until_parked();
2669            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2670            assert!(painted(&state, TextLeafKey::block(5), cx).is_empty());
2671
2672            let state = self::state("ERROR a\n\nERROR b\n\nERROR c", cx);
2673            set(&state, [8..15], cx).unwrap();
2674            state.update(cx, |state, cx| state.set_text("ERROR b\n\nERROR c", cx));
2675            cx.run_until_parked();
2676            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..7]);
2677            assert!(painted(&state, TextLeafKey::block(9), cx).is_empty());
2678        }
2679
2680        #[wgpui::test]
2681        fn appending_a_copy_of_the_last_block_keeps_the_highlight_on_it(cx: &mut TestAppContext) {
2682            let state = state("a\n\nfoo", cx);
2683            // "a\nfoo\n"
2684            set(&state, [2..5], cx).unwrap();
2685            state.update(cx, |state, cx| state.set_text("a\n\nfoo\n\nfoo", cx));
2686            cx.run_until_parked();
2687            assert_eq!(painted(&state, TextLeafKey::block(3), cx), [0..3]);
2688            assert!(painted(&state, TextLeafKey::block(8), cx).is_empty());
2689        }
2690
2691        #[wgpui::test]
2692        fn deleting_a_table_row_drops_highlights_in_the_rows_it_moves(cx: &mut TestAppContext) {
2693            let table = "| a | b |\n|---|---|\n| x | 1 |\n| x | 2 |";
2694            let without_middle_row = "| a | b |\n|---|---|\n| x | 2 |";
2695            // "a b\nx 1\nx 2\n\n": the last row's cells, then the middle
2696            // row's "x".
2697            for ranges in [vec![8..9, 10..11], vec![4..5]] {
2698                let state = state(table, cx);
2699                set(&state, [0..1].into_iter().chain(ranges), cx).unwrap();
2700                state.update(cx, |state, cx| state.set_text(without_middle_row, cx));
2701                cx.run_until_parked();
2702                assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2703                for cell in 1..4 {
2704                    assert!(
2705                        painted(&state, TextLeafKey::table_cell(0, cell), cx).is_empty(),
2706                        "cell {cell}"
2707                    );
2708                }
2709            }
2710        }
2711
2712        #[wgpui::test]
2713        fn streaming_table_rows_keeps_the_highlights_of_earlier_rows(cx: &mut TestAppContext) {
2714            let state = state("| a | b |\n|---|---|\n| x | 1 |", cx);
2715            // "a b\nx 1\n\n"
2716            set(&state, [0..1, 4..5], cx).unwrap();
2717            state.update(cx, |state, cx| {
2718                state.set_text("| a | b |\n|---|---|\n| x | 1 |\n| y | 2 |", cx)
2719            });
2720            cx.run_until_parked();
2721            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2722            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 2), cx), [0..1]);
2723        }
2724
2725        #[wgpui::test]
2726        fn an_edit_in_an_earlier_block_keeps_later_highlights(cx: &mut TestAppContext) {
2727            let state = state("one\n\ntwo", cx);
2728            set(&state, [0..3, 4..7], cx).unwrap();
2729            state.update(cx, |state, cx| state.set_text("one!\n\ntwo", cx));
2730            cx.run_until_parked();
2731            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2732            assert_eq!(painted(&state, TextLeafKey::block(6), cx), [0..3]);
2733        }
2734
2735        #[wgpui::test]
2736        fn an_append_after_a_full_update_compares_every_block(cx: &mut TestAppContext) {
2737            let state = state("first\n\nsecond", cx);
2738            set(&state, [0..5], cx).unwrap();
2739            // An append result whose baseline was a full update that has not
2740            // been committed: its earlier blocks are not the current ones.
2741            let options = UpdateOptions {
2742                revision: 0,
2743                pending_text: "FIRST\n\nsecond".to_string(),
2744                append: false,
2745                mode: ParseMode::Replace,
2746                markdown_extensions: Arc::default(),
2747            };
2748            let new = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2749                .unwrap()
2750                .document;
2751            state.update(cx, |state, _| {
2752                state.full_update_revision = state.committed_revision + 1;
2753                let revision = state.committed_revision + 2;
2754                state.reconcile_range_highlights(&new, revision, true);
2755            });
2756            assert!(!has_highlights(&state, cx));
2757        }
2758
2759        #[wgpui::test]
2760        fn streaming_through_set_text_keeps_highlights(cx: &mut TestAppContext) {
2761            let state = state("first\n\nsec", cx);
2762            // "first\nsec\n"
2763            set(&state, [0..5, 6..9], cx).unwrap();
2764            state.update(cx, |state, cx| state.set_text("first\n\nsecond", cx));
2765            cx.run_until_parked();
2766            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2767            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..3]);
2768        }
2769
2770        #[wgpui::test]
2771        fn a_full_parse_merged_with_an_append_compares_every_block(cx: &mut TestAppContext) {
2772            let state = state("", cx);
2773            // The small text is committed at once, and its background parse
2774            // merges with the append into one full parse, in which the
2775            // definition turns the earlier `[foo]` into the link text `foo`.
2776            state.update(cx, |state, cx| {
2777                state.set_text("[foo] and some text\n\nmore", cx);
2778                let text = state.rendered_text();
2779                let some = text.as_str().find("some").unwrap();
2780                state
2781                    .set_range_highlights([highlight(some..some + 4)], cx)
2782                    .unwrap();
2783                state.push_str("\n\n[foo]: https://example.com", cx);
2784            });
2785            cx.run_until_parked();
2786            state.read_with(cx, |state, _| {
2787                assert!(state.rendered_text().as_str().starts_with("foo and some"));
2788            });
2789            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2790        }
2791
2792        #[wgpui::test]
2793        fn a_full_update_before_an_append_drops_replaced_highlights(cx: &mut TestAppContext) {
2794            let state = state("first", cx);
2795            set(&state, [0..5], cx).unwrap();
2796            let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2797            state.update(cx, |state, cx| {
2798                state.set_text(&large, cx);
2799                state.push_str(" tail", cx);
2800            });
2801            cx.run_until_parked();
2802            assert!(!has_highlights(&state, cx));
2803        }
2804
2805        #[wgpui::test]
2806        fn reparsing_unchanged_text_keeps_highlights(cx: &mut TestAppContext) {
2807            let state = state("first", cx);
2808            set(&state, [0..5], cx).unwrap();
2809            state.update(cx, |state, cx| {
2810                state.set_markdown_extensions(
2811                    Arc::new(MarkdownExtensions::default().parser_revision(1)),
2812                    cx,
2813                )
2814            });
2815            cx.run_until_parked();
2816            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2817        }
2818
2819        pub(super) struct Root {
2820            pub(super) state: Entity<TextViewState>,
2821        }
2822
2823        impl Render for Root {
2824            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2825                wgpui::div()
2826                    .w(px(120.))
2827                    .child(crate::text::TextView::new(&self.state).selectable(true))
2828            }
2829        }
2830
2831        #[wgpui::test]
2832        fn highlights_paint_across_inline_code_tables_and_code_blocks(cx: &mut TestAppContext) {
2833            cx.update(crate::init);
2834            let markdown = "wrapping text with `inline code` and a [link](https://x.y) \
2835                            that wraps\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x = 1;\n```";
2836            let (root, cx) = cx.add_window_view(|_, cx| Root {
2837                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
2838            });
2839            cx.run_until_parked();
2840            let state = root.read_with(cx, |root, _| root.state.clone());
2841            let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
2842            let code = text.find("code").unwrap();
2843            let len = text.len();
2844            // Part of the inline code, every character, and the whole text.
2845            let ranges = [code..code + 2]
2846                .into_iter()
2847                .chain(text.char_indices().map(|(ix, c)| ix..ix + c.len_utf8()))
2848                .chain([0..len])
2849                .filter(|range| !text[range.clone()].trim().is_empty());
2850            state.update(cx, |state, cx| {
2851                state
2852                    .set_range_highlights(ranges.map(highlight), cx)
2853                    .unwrap();
2854            });
2855            cx.update(|window, cx| window.draw(cx).clear());
2856            assert_eq!(
2857                painted(&state, TextLeafKey::block(0), cx)[0],
2858                code..code + 2
2859            );
2860        }
2861
2862        /// The ranges of the current rendered text converted from `sources`.
2863        fn converted(
2864            state: &Entity<TextViewState>,
2865            sources: impl IntoIterator<Item = Range<usize>>,
2866            cx: &mut TestAppContext,
2867        ) -> Vec<Option<Range<usize>>> {
2868            state.read_with(cx, |state, _| {
2869                let text = state.rendered_text();
2870                sources
2871                    .into_iter()
2872                    .map(|source| text.range_for_source(source))
2873                    .collect()
2874            })
2875        }
2876
2877        fn find(haystack: &str, needle: &str) -> Range<usize> {
2878            let start = haystack.find(needle).unwrap();
2879            start..start + needle.len()
2880        }
2881
2882        #[wgpui::test]
2883        fn source_ranges_highlight_the_text_rendered_from_them(cx: &mut TestAppContext) {
2884            let markdown =
2885                "In Rust, we use `u128` to handle **larger** numbers\n\n| a | **b** |\n|---|---|";
2886            let state = state(markdown, cx);
2887            state.update(cx, |state, cx| {
2888                let text = state.rendered_text();
2889                assert_eq!(text.source(), markdown);
2890                let highlights = ["`u128` to handle **larger**", "**b**"]
2891                    .into_iter()
2892                    .map(|needle| text.range_for_source(find(markdown, needle)).unwrap())
2893                    .map(highlight)
2894                    .collect::<Vec<_>>();
2895                state.set_range_highlights(highlights, cx).unwrap();
2896            });
2897            let rendered = "In Rust, we use u128 to handle larger numbers";
2898            assert_eq!(
2899                painted(&state, TextLeafKey::block(0), cx),
2900                [find(rendered, "u128 to handle larger")]
2901            );
2902            let table = markdown.find("| a").unwrap();
2903            assert_eq!(
2904                painted(&state, TextLeafKey::table_cell(table, 1), cx),
2905                [0..1]
2906            );
2907        }
2908
2909        #[wgpui::test]
2910        fn select_all_converts_to_every_rendered_character(cx: &mut TestAppContext) {
2911            let markdown = "# Title\n\nhello **world**\n\n- item";
2912            let state = state(markdown, cx);
2913            state.update(cx, |state, cx| state.select_all(cx));
2914            state.read_with(cx, |state, _| {
2915                let text = state.rendered_text();
2916                assert_eq!(text.as_str(), "Title\nhello world\nitem\n");
2917                let source = state.selected_source_range().unwrap();
2918                // All but the separator after the last block.
2919                assert_eq!(text.range_for_source(source), Some(0..text.len() - 1));
2920            });
2921        }
2922
2923        #[wgpui::test]
2924        fn a_snapshot_converts_against_its_own_source(cx: &mut TestAppContext) {
2925            let state = state("first", cx);
2926            let before = state.read_with(cx, |state, _| state.rendered_text());
2927            state.update(cx, |state, cx| state.push_str("\n\nsecond **part**", cx));
2928            let source = "first\n\nsecond **part**";
2929            let second = find(source, "second **part**");
2930
2931            // The append is parsed in the background, so until it lands the
2932            // view renders the source it had.
2933            state.read_with(cx, |state, _| {
2934                let text = state.rendered_text();
2935                assert_eq!(text, before);
2936                assert_eq!(text.source(), "first");
2937                assert_eq!(text.range_for_source(second.clone()), None);
2938            });
2939            cx.run_until_parked();
2940
2941            assert_eq!(
2942                converted(&state, [second.clone(), 0..5], cx),
2943                [Some(6..17), Some(0..5)]
2944            );
2945            state.read_with(cx, |state, _| {
2946                let text = state.rendered_text();
2947                assert_ne!(text, before);
2948                assert_eq!(text.source(), source);
2949                assert_eq!(&text.as_str()[6..17], "second part");
2950            });
2951            // An earlier snapshot keeps converting against its own source.
2952            assert_eq!(before.source(), "first");
2953            assert_eq!(before.range_for_source(0..5), Some(0..5));
2954            assert_eq!(before.range_for_source(second), None);
2955        }
2956
2957        #[wgpui::test]
2958        fn appended_blocks_convert_at_their_place_in_the_whole_source(cx: &mut TestAppContext) {
2959            let state = state("first\n\nsecond", cx);
2960            // The tail parse reparses from the last block, whose positions
2961            // must still count from the start of the whole source.
2962            state.update(cx, |state, cx| state.push_str(" more\n\n**écho** end", cx));
2963            cx.run_until_parked();
2964            let source = "first\n\nsecond more\n\n**écho** end";
2965            let converted = converted(
2966                &state,
2967                [
2968                    find(source, "second more"),
2969                    find(source, "**écho**"),
2970                    find(source, "end"),
2971                ],
2972                cx,
2973            );
2974            state.read_with(cx, |state, _| {
2975                let text = state.rendered_text();
2976                assert_eq!(text.source(), source);
2977                let texts = converted
2978                    .into_iter()
2979                    .map(|range| &text.as_str()[range.unwrap()])
2980                    .collect::<Vec<_>>();
2981                assert_eq!(texts, ["second more", "écho", "end"]);
2982            });
2983        }
2984
2985        #[wgpui::test]
2986        fn a_background_parse_converts_once_it_lands(cx: &mut TestAppContext) {
2987            cx.update(crate::init);
2988            let markdown = format!(
2989                "{}\n\n**tail**",
2990                "word ".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 4)
2991            );
2992            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(&markdown, cx)));
2993            let tail = find(&markdown, "**tail**");
2994            state.read_with(cx, |state, _| {
2995                let text = state.rendered_text();
2996                assert!(text.source().is_empty());
2997                assert!(text.is_empty());
2998                assert_eq!(text.range_for_source(tail.clone()), None);
2999            });
3000            cx.run_until_parked();
3001            state.read_with(cx, |state, _| {
3002                let text = state.rendered_text();
3003                assert_eq!(text.source(), markdown);
3004                let range = text.range_for_source(tail).unwrap();
3005                assert_eq!(&text.as_str()[range], "tail");
3006            });
3007        }
3008
3009        #[wgpui::test]
3010        fn inline_objects_convert_whole_and_stay_unpainted(cx: &mut TestAppContext) {
3011            let markdown = "x $ab$ y";
3012            let state = state(markdown, cx);
3013            state.update(cx, |state, cx| {
3014                let extensions = MarkdownExtensions::default().plugin(
3015                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
3016                        |node, _| {
3017                            let markdown::mdast::Node::InlineMath(math) = node else {
3018                                return None;
3019                            };
3020                            Some(
3021                                crate::text::MarkdownNode::new("formula", ())
3022                                    .text(math.value.clone()),
3023                            )
3024                        },
3025                    ),
3026                );
3027                state.set_markdown_extensions(Arc::new(extensions), cx);
3028            });
3029            cx.run_until_parked();
3030            // "x ab y\n", where "ab" is the formula.
3031            let formula = find(markdown, "$ab$");
3032            assert_eq!(
3033                converted(
3034                    &state,
3035                    [
3036                        formula.clone(),
3037                        formula.start + 1..formula.start + 2,
3038                        0..markdown.len(),
3039                        find(markdown, "ab$ y"),
3040                    ],
3041                    cx
3042                ),
3043                [Some(2..4), Some(2..4), Some(0..6), Some(2..6)]
3044            );
3045            let ranges = converted(&state, [formula, 0..markdown.len()], cx);
3046            set(&state, [ranges[0].clone().unwrap()], cx).unwrap();
3047            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
3048            set(&state, [ranges[1].clone().unwrap()], cx).unwrap();
3049            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..2, 4..6]);
3050        }
3051
3052        #[wgpui::test]
3053        fn a_dragged_selection_highlights_through_its_source_range(cx: &mut TestAppContext) {
3054            struct SelectionRoot {
3055                state: Entity<TextViewState>,
3056            }
3057
3058            impl Render for SelectionRoot {
3059                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3060                    wgpui::div()
3061                        .w(px(160.))
3062                        .child(crate::TextSelectionLayer)
3063                        .child(crate::text::TextView::new(&self.state))
3064                }
3065            }
3066
3067            cx.update(crate::init);
3068            let markdown = "hello **world** and `code` &amp; more";
3069            let (root, cx) = cx.add_window_view(|_, cx| SelectionRoot {
3070                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3071            });
3072            cx.run_until_parked();
3073            let state = root.read_with(cx, |root, _| root.state.clone());
3074            cx.update(|window, cx| window.draw(cx).clear());
3075            let bounds = state.read_with(cx, |state, _| state.bounds());
3076            assert!(bounds.size.height > px(30.), "the text wraps, {bounds:?}");
3077            let start = bounds.origin + wgpui::point(px(2.), px(4.));
3078            let end = bounds.bottom_right() - wgpui::point(px(2.), px(4.));
3079            cx.simulate_mouse_down(start, wgpui::MouseButton::Left, wgpui::Modifiers::default());
3080            cx.update(|window, cx| window.draw(cx).clear());
3081            cx.simulate_mouse_move(end, wgpui::MouseButton::Left, wgpui::Modifiers::default());
3082            cx.update(|window, cx| window.draw(cx).clear());
3083            cx.simulate_mouse_up(end, wgpui::MouseButton::Left, wgpui::Modifiers::default());
3084            cx.update(|window, cx| window.draw(cx).clear());
3085
3086            let range = state.update(cx, |state, cx| {
3087                let selected = state.selected_text();
3088                let source = state
3089                    .selected_source_range()
3090                    .expect("selection maps to source");
3091                let text = state.rendered_text();
3092                let range = text.range_for_source(source).expect("source renders text");
3093                assert!(selected.contains("code &"), "selected {selected:?}");
3094                assert_eq!(
3095                    &text.as_str()[range.clone()],
3096                    selected.trim_end_matches('\n')
3097                );
3098                state.clear_selection(cx);
3099                state
3100                    .set_range_highlights([highlight(range.clone())], cx)
3101                    .unwrap();
3102                range
3103            });
3104            cx.update(|window, cx| window.draw(cx).clear());
3105            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [range]);
3106        }
3107
3108        #[wgpui::test]
3109        fn html_views_convert_no_source(cx: &mut TestAppContext) {
3110            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
3111            cx.run_until_parked();
3112            html.read_with(cx, |html, _| {
3113                let text = html.rendered_text();
3114                assert_eq!(text.source(), "<p>one</p>");
3115                assert_eq!(text.range_for_source(0..10), None);
3116                assert_eq!(text.range_for_source(3..6), None);
3117            });
3118        }
3119
3120        #[wgpui::test]
3121        fn clear_range_highlights_removes_them(cx: &mut TestAppContext) {
3122            let state = state("first", cx);
3123            set(&state, [0..5], cx).unwrap();
3124            state.update(cx, |state, cx| state.clear_range_highlights(cx));
3125            assert!(!has_highlights(&state, cx));
3126        }
3127    }
3128
3129    mod reveal_range {
3130        use wgpui::{
3131            Entity, InteractiveElement as _, ListAlignment, ListState, ScrollHandle,
3132            StatefulInteractiveElement as _, TestAppContext, VisualTestContext, div, list,
3133        };
3134
3135        use super::super::*;
3136        use crate::text::TextView;
3137
3138        /// Where the view sits in a 200 × 100 window.
3139        #[derive(Clone)]
3140        enum Container {
3141            /// A scrollable view.
3142            Scrollable,
3143            /// A fit-content view, second row of an application list.
3144            List(ListState),
3145            /// A fit-content view in a scrolling `div`, which follows reveals
3146            /// through `on_reveal`.
3147            Div(ScrollHandle),
3148            /// A fit-content view clamped to two lines, second row of a list.
3149            Clamped(ListState),
3150            /// A fit-content view in nothing that scrolls.
3151            Fixed,
3152        }
3153
3154        struct Root {
3155            state: Entity<TextViewState>,
3156            container: Container,
3157        }
3158
3159        impl Render for Root {
3160            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3161                let state = self.state.clone();
3162                let frame = div().w(px(200.)).h(px(100.));
3163                let row = |list_state: &ListState, clamp: bool| {
3164                    let state = state.clone();
3165                    list(list_state.clone(), move |ix, _, _| match ix {
3166                        0 => div().h(px(40.)).into_any_element(),
3167                        _ => TextView::new(&state)
3168                            .when(clamp, |view| view.max_lines(2))
3169                            .into_any_element(),
3170                    })
3171                    .size_full()
3172                };
3173                match &self.container {
3174                    Container::Scrollable => frame
3175                        .child(TextView::new(&state).scrollable(true))
3176                        .into_any_element(),
3177                    Container::List(list_state) => {
3178                        frame.child(row(list_state, false)).into_any_element()
3179                    }
3180                    Container::Clamped(list_state) => {
3181                        frame.child(row(list_state, true)).into_any_element()
3182                    }
3183                    Container::Div(handle) => {
3184                        let scroll = handle.clone();
3185                        frame
3186                            .child(
3187                                div()
3188                                    .id("scroll")
3189                                    .size_full()
3190                                    .overflow_y_scroll()
3191                                    .track_scroll(handle)
3192                                    .child(TextView::new(&state).on_reveal(move |line, _, _| {
3193                                        let viewport = scroll.bounds();
3194                                        let mut offset = scroll.offset();
3195                                        if line.bottom() > viewport.bottom() {
3196                                            offset.y -= line.bottom() - viewport.bottom();
3197                                        } else if line.top() < viewport.top() {
3198                                            offset.y += viewport.top() - line.top();
3199                                        }
3200                                        scroll.set_offset(offset);
3201                                    })),
3202                            )
3203                            .into_any_element()
3204                    }
3205                    Container::Fixed => frame.child(TextView::new(&state)).into_any_element(),
3206                }
3207            }
3208        }
3209
3210        fn window<'a>(
3211            markdown: &str,
3212            container: Container,
3213            cx: &'a mut TestAppContext,
3214        ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
3215            cx.update(crate::init);
3216            let (root, cx) = cx.add_window_view(|_, cx| Root {
3217                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3218                container,
3219            });
3220            cx.run_until_parked();
3221            draw(cx);
3222            let state = root.read_with(cx, |root, _| root.state.clone());
3223            (state, cx)
3224        }
3225
3226        fn draw(cx: &mut VisualTestContext) {
3227            cx.update(|window, cx| window.draw(cx).clear());
3228        }
3229
3230        /// Asks to reveal the first occurrence of `needle`, then runs `then`
3231        /// before anything is drawn.
3232        fn request(
3233            state: &Entity<TextViewState>,
3234            needle: &str,
3235            cx: &mut VisualTestContext,
3236            then: impl FnOnce(&mut TextViewState, &mut Context<TextViewState>),
3237        ) {
3238            state.update(cx, |state, cx| {
3239                let text = state.rendered_text();
3240                let start = text.as_str().find(needle).unwrap();
3241                state.reveal_range(start..start + needle.len(), cx).unwrap();
3242                then(state, cx);
3243            });
3244        }
3245
3246        /// Reveals the first occurrence of `needle` and draws a few frames.
3247        fn reveal(state: &Entity<TextViewState>, needle: &str, cx: &mut VisualTestContext) {
3248            request(state, needle, cx, |_, _| {});
3249            for _ in 0..3 {
3250                draw(cx);
3251            }
3252        }
3253
3254        fn is_pending(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> bool {
3255            state.read_with(cx, |state, _| state.pending_reveal.is_some())
3256        }
3257
3258        fn scroll_top(
3259            state: &Entity<TextViewState>,
3260            cx: &mut VisualTestContext,
3261        ) -> wgpui::ListOffset {
3262            state.read_with(cx, |state, _| state.list_state.logical_scroll_top())
3263        }
3264
3265        fn paragraphs(count: usize) -> String {
3266            (0..count)
3267                .map(|ix| format!("paragraph {ix}"))
3268                .collect::<Vec<_>>()
3269                .join("\n\n")
3270        }
3271
3272        fn words(count: usize) -> String {
3273            (0..count)
3274                .map(|ix| format!("w{ix}"))
3275                .collect::<Vec<_>>()
3276                .join(" ")
3277        }
3278
3279        #[wgpui::test]
3280        fn a_scrollable_view_scrolls_to_an_offscreen_block(cx: &mut TestAppContext) {
3281            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3282            reveal(&state, "paragraph 150", cx);
3283            assert!(!is_pending(&state, cx));
3284            let top = scroll_top(&state, cx);
3285            assert!((140..=150).contains(&top.item_ix), "{top:?}");
3286
3287            reveal(&state, "paragraph 3", cx);
3288            assert!(!is_pending(&state, cx));
3289            assert!(scroll_top(&state, cx).item_ix <= 3);
3290        }
3291
3292        #[wgpui::test]
3293        fn an_append_adding_blocks_keeps_the_scroll_position(cx: &mut TestAppContext) {
3294            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3295            reveal(&state, "paragraph 100", cx);
3296            let top = scroll_top(&state, cx);
3297            assert!(top.item_ix > 0, "{top:?}");
3298
3299            state.update(cx, |state, cx| state.push_str("\n\nparagraph 200", cx));
3300            cx.run_until_parked();
3301            draw(cx);
3302
3303            state.read_with(cx, |state, _| {
3304                assert_eq!(state.list_state.item_count(), 201);
3305            });
3306            assert_unmoved(&state, top, cx);
3307        }
3308
3309        #[wgpui::test]
3310        fn a_scrollable_view_scrolls_to_a_line_inside_a_long_paragraph(cx: &mut TestAppContext) {
3311            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3312            reveal(&state, "w390", cx);
3313            assert!(!is_pending(&state, cx));
3314            let top = scroll_top(&state, cx);
3315            assert_eq!(top.item_ix, 0);
3316            assert!(top.offset_in_item > px(100.), "{top:?}");
3317        }
3318
3319        #[wgpui::test]
3320        fn revealing_a_visible_line_does_not_scroll(cx: &mut TestAppContext) {
3321            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3322            reveal(&state, "w200", cx);
3323            let top = scroll_top(&state, cx);
3324            assert!(top.offset_in_item > px(0.), "{top:?}");
3325            for word in ["w199", "w198", "w197", "w196"] {
3326                reveal(&state, word, cx);
3327                assert!(!is_pending(&state, cx));
3328                let now = scroll_top(&state, cx);
3329                assert_eq!(
3330                    (now.item_ix, now.offset_in_item),
3331                    (top.item_ix, top.offset_in_item),
3332                    "{word}"
3333                );
3334            }
3335        }
3336
3337        #[wgpui::test]
3338        fn an_enclosing_list_scrolls_to_a_line_of_a_fit_content_view(cx: &mut TestAppContext) {
3339            let outer = ListState::new(2, ListAlignment::Top, px(1000.));
3340            let (state, cx) = window(&words(400), Container::List(outer.clone()), cx);
3341            reveal(&state, "w390", cx);
3342            assert!(!is_pending(&state, cx));
3343            let top = outer.logical_scroll_top();
3344            assert_eq!(top.item_ix, 1, "{top:?}");
3345            assert!(top.offset_in_item > px(100.), "{top:?}");
3346        }
3347
3348        #[wgpui::test]
3349        fn on_reveal_scrolls_a_container_that_ignores_scroll_requests(cx: &mut TestAppContext) {
3350            let handle = ScrollHandle::new();
3351            let (state, cx) = window(&words(400), Container::Div(handle.clone()), cx);
3352            reveal(&state, "w390", cx);
3353            assert!(!is_pending(&state, cx));
3354            assert!(handle.offset().y < px(-100.), "{:?}", handle.offset());
3355        }
3356
3357        #[wgpui::test]
3358        fn a_reveal_that_cannot_be_shown_gives_up(cx: &mut TestAppContext) {
3359            let (state, cx) = window(&words(4000), Container::Fixed, cx);
3360            reveal(&state, "w3990", cx);
3361            assert!(is_pending(&state, cx));
3362            for _ in 0..10 {
3363                draw(cx);
3364            }
3365            assert!(!is_pending(&state, cx));
3366        }
3367
3368        #[wgpui::test]
3369        fn a_reveal_not_carried_out_in_time_is_dropped(cx: &mut TestAppContext) {
3370            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3371            request(&state, "paragraph 150", cx, |_, cx| {
3372                cx.background_executor()
3373                    .advance_clock(std::time::Duration::from_secs(2))
3374            });
3375            draw(cx);
3376            assert!(!is_pending(&state, cx));
3377            assert_eq!(scroll_top(&state, cx).item_ix, 0);
3378        }
3379
3380        #[wgpui::test]
3381        fn an_empty_range_reveals_its_line(cx: &mut TestAppContext) {
3382            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3383            reveal(&state, "w390", cx);
3384            let top = scroll_top(&state, cx);
3385            // A position on a visible line leaves the view where it is.
3386            state.update(cx, |state, cx| {
3387                let text = state.rendered_text();
3388                let start = text.as_str().find("w391").unwrap();
3389                state.reveal_range(start..start, cx).unwrap();
3390            });
3391            for _ in 0..3 {
3392                draw(cx);
3393            }
3394            assert!(!is_pending(&state, cx));
3395            let now = scroll_top(&state, cx);
3396            assert_eq!(
3397                (now.item_ix, now.offset_in_item),
3398                (top.item_ix, top.offset_in_item)
3399            );
3400        }
3401
3402        #[wgpui::test]
3403        fn a_position_after_the_last_character_reveals_its_line(cx: &mut TestAppContext) {
3404            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3405            reveal(&state, "w399", cx);
3406            let top = scroll_top(&state, cx);
3407            assert!(top.offset_in_item > px(1000.), "{top:?}");
3408            // The end of the text, on the visible last line.
3409            state.update(cx, |state, cx| {
3410                let text = state.rendered_text();
3411                let end = text.as_str().find("w399").unwrap() + "w399".len();
3412                state.reveal_range(end..end, cx).unwrap();
3413            });
3414            for _ in 0..3 {
3415                draw(cx);
3416            }
3417            assert!(!is_pending(&state, cx));
3418            let now = scroll_top(&state, cx);
3419            assert_eq!(
3420                (now.item_ix, now.offset_in_item),
3421                (top.item_ix, top.offset_in_item)
3422            );
3423        }
3424
3425        /// Reveals `range` of the current text and draws a few frames.
3426        fn reveal_at(
3427            state: &Entity<TextViewState>,
3428            range: impl FnOnce(&str) -> std::ops::Range<usize>,
3429            cx: &mut VisualTestContext,
3430        ) {
3431            state.update(cx, |state, cx| {
3432                let text = state.rendered_text();
3433                let range = range(text.as_str());
3434                state.reveal_range(range, cx).unwrap();
3435            });
3436            for _ in 0..3 {
3437                draw(cx);
3438            }
3439        }
3440
3441        fn assert_unmoved(
3442            state: &Entity<TextViewState>,
3443            top: wgpui::ListOffset,
3444            cx: &mut VisualTestContext,
3445        ) {
3446            assert!(!is_pending(state, cx));
3447            let now = scroll_top(state, cx);
3448            assert_eq!(
3449                (now.item_ix, now.offset_in_item),
3450                (top.item_ix, top.offset_in_item)
3451            );
3452        }
3453
3454        #[wgpui::test]
3455        fn the_end_of_the_text_and_its_separators_reveal_the_last_line(cx: &mut TestAppContext) {
3456            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3457            reveal(&state, "w399", cx);
3458            let top = scroll_top(&state, cx);
3459            assert!(top.offset_in_item > px(1000.), "{top:?}");
3460            // The end of the text, after the separator that ends the block.
3461            reveal_at(&state, |text| text.len()..text.len(), cx);
3462            assert_unmoved(&state, top, cx);
3463            // Only that separator.
3464            reveal_at(&state, |text| text.len() - 1..text.len(), cx);
3465            assert_unmoved(&state, top, cx);
3466
3467            let code = (0..200)
3468                .map(|ix| format!("line {ix}"))
3469                .collect::<Vec<_>>()
3470                .join("\n");
3471            state.update(cx, |state, cx| {
3472                state.set_text(&format!("```\n{code}\n```"), cx)
3473            });
3474            cx.run_until_parked();
3475            reveal(&state, "line 199", cx);
3476            let top = scroll_top(&state, cx);
3477            assert!(top.offset_in_item > px(1000.), "{top:?}");
3478            reveal_at(&state, |text| text.len()..text.len(), cx);
3479            assert_unmoved(&state, top, cx);
3480        }
3481
3482        #[wgpui::test]
3483        fn the_end_of_a_block_above_reveals_its_last_line(cx: &mut TestAppContext) {
3484            let second = (0..400)
3485                .map(|ix| format!("v{ix}"))
3486                .collect::<Vec<_>>()
3487                .join(" ");
3488            let markdown = format!("{}\n\n{second}", words(400));
3489            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3490            reveal(&state, "v399", cx);
3491            assert_eq!(scroll_top(&state, cx).item_ix, 1);
3492            // The end of the first paragraph, on the separator after it.
3493            reveal_at(
3494                &state,
3495                |text| {
3496                    let end = text.find("w399").unwrap() + "w399".len();
3497                    end..end
3498                },
3499                cx,
3500            );
3501            assert!(!is_pending(&state, cx));
3502            let top = scroll_top(&state, cx);
3503            assert_eq!(top.item_ix, 0, "{top:?}");
3504            assert!(top.offset_in_item > px(1000.), "{top:?}");
3505        }
3506
3507        #[wgpui::test]
3508        fn an_empty_view_has_nothing_to_reveal(cx: &mut TestAppContext) {
3509            cx.update(crate::init);
3510            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
3511            cx.run_until_parked();
3512            state.update(cx, |state, cx| {
3513                assert_eq!(state.reveal_range(0..0, cx), Ok(()));
3514                assert!(state.pending_reveal.is_none());
3515            });
3516        }
3517
3518        #[wgpui::test]
3519        fn revealing_a_visible_block_does_not_scroll(cx: &mut TestAppContext) {
3520            let markdown = format!("{}\n\n<div>html</div>\n\n{}", words(400), words(400));
3521            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3522            reveal(&state, "html", cx);
3523            // Still in view a little further down.
3524            state.update(cx, |state, _| state.list_state.scroll_by(px(30.)));
3525            draw(cx);
3526            let top = scroll_top(&state, cx);
3527            reveal(&state, "html", cx);
3528            assert_unmoved(&state, top, cx);
3529        }
3530
3531        #[wgpui::test]
3532        fn a_line_of_an_inline_flow_counts_as_shown_once_scrolled_to(cx: &mut TestAppContext) {
3533            // Inline code every tenth word, so the rows are taller than the
3534            // body line and land between pixels.
3535            let markdown = (0..400)
3536                .map(|ix| {
3537                    if ix % 10 == 0 {
3538                        format!("`c{ix}`")
3539                    } else {
3540                        format!("w{ix}")
3541                    }
3542                })
3543                .collect::<Vec<_>>()
3544                .join(" ");
3545            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3546            reveal(&state, "c390", cx);
3547            assert!(!is_pending(&state, cx));
3548            assert!(scroll_top(&state, cx).offset_in_item > px(1000.));
3549        }
3550
3551        #[wgpui::test]
3552        fn a_range_starting_on_a_line_break_reveals_the_next_line(cx: &mut TestAppContext) {
3553            let code = (0..200)
3554                .map(|ix| format!("line {ix}"))
3555                .collect::<Vec<_>>()
3556                .join("\n");
3557            let (state, cx) = window(&format!("```\n{code}\n```"), Container::Scrollable, cx);
3558            reveal(&state, "\nline 190", cx);
3559            assert!(!is_pending(&state, cx));
3560            let top = scroll_top(&state, cx);
3561            assert!(top.offset_in_item > px(1000.), "{top:?}");
3562        }
3563
3564        #[wgpui::test]
3565        fn a_range_starting_on_a_line_break_in_an_inline_flow_reveals_the_next_line(
3566            cx: &mut TestAppContext,
3567        ) {
3568            // Inline code lays the paragraph out as an inline flow.
3569            let lines = (0..200)
3570                .map(|ix| format!("line {ix} `code`"))
3571                .collect::<Vec<_>>()
3572                .join("\\\n");
3573            let (state, cx) = window(&lines, Container::Scrollable, cx);
3574            reveal(&state, "\nline 190", cx);
3575            assert!(!is_pending(&state, cx));
3576            let top = scroll_top(&state, cx);
3577            assert!(top.offset_in_item > px(1000.), "{top:?}");
3578        }
3579
3580        #[wgpui::test]
3581        fn a_reveal_is_dropped_when_its_text_before_it_changes(cx: &mut TestAppContext) {
3582            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3583            let target = "first words then the target";
3584            let markdown = format!("{target}\n\n{}", paragraphs(200));
3585            state.update(cx, |state, cx| state.set_text(&markdown, cx));
3586            cx.run_until_parked();
3587
3588            // Appending to its paragraph keeps it.
3589            request(&state, "target", cx, |state, cx| {
3590                state.set_text(&markdown.replacen("target", "target and more", 1), cx);
3591                assert!(state.pending_reveal.is_some());
3592            });
3593            // An edit before it in its paragraph drops it.
3594            request(&state, "target", cx, |state, cx| {
3595                state.set_text(&markdown.replacen("words", "WORDS", 1), cx);
3596                assert!(state.pending_reveal.is_none());
3597            });
3598        }
3599
3600        #[wgpui::test]
3601        fn a_clamped_view_does_not_reveal(cx: &mut TestAppContext) {
3602            let outer = ListState::new(2, ListAlignment::Top, px(1000.));
3603            let (state, cx) = window(&words(400), Container::Clamped(outer.clone()), cx);
3604            reveal(&state, "w390", cx);
3605            assert!(!is_pending(&state, cx));
3606            assert_eq!(outer.logical_scroll_top().item_ix, 0);
3607        }
3608
3609        #[wgpui::test]
3610        fn text_outside_every_block_reveals_its_block(cx: &mut TestAppContext) {
3611            let markdown = format!("{}\n\n<div>html text</div>", paragraphs(100));
3612            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3613            reveal(&state, "html text", cx);
3614            assert!(!is_pending(&state, cx));
3615            assert!(
3616                scroll_top(&state, cx).item_ix >= 90,
3617                "{:?}",
3618                scroll_top(&state, cx)
3619            );
3620        }
3621
3622        #[wgpui::test]
3623        fn a_reveal_follows_its_text_past_an_edit_before_it(cx: &mut TestAppContext) {
3624            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3625            // An inserted paragraph moves the target down one block.
3626            request(&state, "paragraph 150", cx, |state, cx| {
3627                state.set_text(&format!("inserted\n\n{}", paragraphs(200)), cx);
3628                assert!(state.pending_reveal.is_some());
3629            });
3630            for _ in 0..3 {
3631                draw(cx);
3632            }
3633            assert!(!is_pending(&state, cx));
3634            let top = scroll_top(&state, cx);
3635            assert!((141..=151).contains(&top.item_ix), "{top:?}");
3636
3637            // A reveal whose text changed is dropped.
3638            request(&state, "paragraph 150", cx, |state, cx| {
3639                state.set_text(&paragraphs(200).replace("paragraph 150", "changed"), cx);
3640                assert!(state.pending_reveal.is_none());
3641            });
3642        }
3643
3644        #[wgpui::test]
3645        fn malformed_ranges_and_html_views_are_rejected(cx: &mut TestAppContext) {
3646            cx.update(crate::init);
3647            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("first\n\nsecond", cx)));
3648            cx.run_until_parked();
3649            state.update(cx, |state, cx| {
3650                assert_eq!(
3651                    state.reveal_range(std::ops::Range { start: 5, end: 3 }, cx),
3652                    Err(RangeHighlightError::InvalidRange(0))
3653                );
3654                assert_eq!(
3655                    state.reveal_range(0..100, cx),
3656                    Err(RangeHighlightError::InvalidRange(0))
3657                );
3658                state.reveal_range(0..5, cx).unwrap();
3659            });
3660
3661            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
3662            cx.run_until_parked();
3663            html.update(cx, |html, cx| {
3664                assert_eq!(
3665                    html.reveal_range(0..3, cx),
3666                    Err(RangeHighlightError::Unsupported)
3667                );
3668            });
3669        }
3670    }
3671}