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 gpui::{
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 v_flex,
37};
38
39const CONTEXT: &'static str = "TextView";
40const MAX_COALESCED_UPDATES_PER_PARSE: usize = 64;
42const MAX_SYNC_FULL_REPLACE_BYTES: usize = 4 * 1024;
45const STREAM_FADE_TICK: Duration = Duration::from_millis(33);
47
48pub(crate) fn init(cx: &mut App) {
49 cx.bind_keys(vec![
50 #[cfg(target_os = "macos")]
51 KeyBinding::new("cmd-c", input::Copy, Some(CONTEXT)),
52 #[cfg(not(target_os = "macos"))]
53 KeyBinding::new("ctrl-c", input::Copy, Some(CONTEXT)),
54 #[cfg(target_os = "macos")]
55 KeyBinding::new("cmd-a", input::SelectAll, Some(CONTEXT)),
56 #[cfg(not(target_os = "macos"))]
57 KeyBinding::new("ctrl-a", input::SelectAll, Some(CONTEXT)),
58 ]);
59}
60
61#[derive(Clone, Copy, PartialEq, Eq)]
63pub(super) enum TextViewFormat {
64 Markdown,
66 Html,
68}
69
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
74pub enum SelectionFormat {
75 #[default]
77 Plain,
78 Source,
84}
85
86#[derive(Clone, Copy)]
90pub(super) struct LineSpan {
91 pub(super) top: Pixels,
92 pub(super) bottom: Pixels,
93 pub(super) line_height: Pixels,
94}
95
96pub struct TextViewState {
98 entity_id: EntityId,
99 pub(super) focus_handle: FocusHandle,
100 pub(super) list_state: ListState,
101
102 bounds: Bounds<Pixels>,
104
105 pub(super) selectable: bool,
106 pub(super) selection_format: SelectionFormat,
107 pub(super) scrollable: bool,
108 pub(super) max_lines: Option<usize>,
109 pub(super) line_spans: Arc<Mutex<Vec<LineSpan>>>,
112 pub(super) clamped: bool,
114 pub(super) text_view_style: Arc<TextViewStyle>,
115 pub(super) code_block_actions: Option<std::sync::Arc<CodeBlockActionsFn>>,
116 pub(super) code_block_highlighter: Option<std::sync::Arc<CodeBlockHighlighterFn>>,
117 pub(super) table_actions: Option<std::sync::Arc<TableActionsFn>>,
118 pub(super) image_source: Option<std::sync::Arc<super::text_view::ImageSourceFn>>,
119 pub(super) link_click_handler: Option<std::sync::Arc<LinkClickHandlerFn>>,
120 pub(super) markdown_extensions: Arc<MarkdownExtensions>,
121
122 pub(super) is_selecting: bool,
123 pub(super) preserve_inline_selection: bool,
125 multi_click_selection: Option<TextViewMultiClickSelection>,
126 selected_text_override: Option<String>,
127 select_all: bool,
128 pub(super) auto_scroll: AutoScroll,
129 pub(super) selection_adapter: TextViewSelectionAdapter,
130
131 pub(super) parsed_content: ParsedContent,
132 pub(super) stream_fade: StreamFadeTracker,
133 fade_tick: Option<Task<()>>,
134 format: TextViewFormat,
137 text: String,
138 element_text: Option<SharedString>,
141 revision: usize,
142 committed_revision: usize,
144 full_update_revision: usize,
147 rendered_index: Arc<OnceLock<RenderedIndex>>,
149 range_highlights: Option<Arc<RangeHighlightFrame>>,
150 pub(super) pending_reveal: Option<PendingReveal>,
151 pub(super) selection_revision: usize,
152 compatible_layout_update: bool,
153 layout_text_style: Option<(gpui::TextStyle, Pixels)>,
154 parsed_error: Option<SharedString>,
155 tx: Sender<UpdateOptions>,
156 _parse_task: Task<()>,
157 _receive_task: Task<()>,
158}
159
160impl TextViewState {
161 pub fn markdown(text: &str, cx: &mut Context<Self>) -> Self {
163 Self::new(TextViewFormat::Markdown, text, cx)
164 }
165
166 pub fn html(text: &str, cx: &mut Context<Self>) -> Self {
168 Self::new(TextViewFormat::Html, text, cx)
169 }
170
171 fn new(format: TextViewFormat, text: &str, cx: &mut Context<Self>) -> Self {
173 let focus_handle = cx.focus_handle();
174 let selection_adapter = TextViewSelectionAdapter::new(cx.entity().downgrade(), cx);
175
176 let (tx, rx) = unbounded::<UpdateOptions>();
177 let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
178 let _receive_task = cx.spawn({
179 async move |weak_self, cx| {
180 while let Ok(parsed_update) = rx_result.recv().await {
181 _ = weak_self.update(cx, |state, cx| {
182 if parsed_update.revision != state.revision {
183 return;
184 }
185 if parsed_update.baseline_ack {
186 debug_assert!(parsed_update.full_parse);
187 return;
188 }
189
190 match parsed_update.result {
191 Ok(content) => {
192 let append =
193 parsed_update.selection_compatible && !parsed_update.full_parse;
194 if append && state.full_update_revision <= state.committed_revision
195 {
196 state.splice_appended_blocks(&content.document);
197 }
198 state.reconcile_range_highlights(
199 &content.document,
200 parsed_update.revision,
201 append,
202 );
203 state.stream_fade.record(
204 &state.parsed_content.document,
205 &content.document,
206 Instant::now(),
207 );
208 state.parsed_content = content;
209 state.parsed_error = None;
210 state.compatible_layout_update = parsed_update.selection_compatible;
211 if parsed_update.full_parse {
212 state.invalidate_measured_heights();
213 }
214 }
215 Err(err) => {
216 state.stream_fade.discard_pending();
217 state.parsed_error = Some(err);
218 }
219 }
220 if !parsed_update.selection_compatible && !state.is_selecting {
224 state.reset_selection_and_adapter(cx);
225 }
226 cx.notify();
227 });
228 }
229 }
230 });
231
232 let _parse_task = cx.background_spawn(UpdateFuture::new(format, rx, tx_result));
233
234 let mut this = Self {
235 entity_id: cx.entity_id(),
236 focus_handle,
237 bounds: Bounds::default(),
238 multi_click_selection: None,
239 selected_text_override: None,
240 select_all: false,
241 selectable: false,
242 selection_format: SelectionFormat::default(),
243 scrollable: false,
244 max_lines: None,
245 line_spans: Arc::default(),
246 clamped: false,
247 list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)).measure_all(),
252 text_view_style: Arc::default(),
253 code_block_actions: None,
254 code_block_highlighter: None,
255 table_actions: None,
256 link_click_handler: None,
257 image_source: None,
258 markdown_extensions: Arc::default(),
259 is_selecting: false,
260 preserve_inline_selection: false,
261 auto_scroll: AutoScroll::default(),
262 selection_adapter,
263 parsed_content: Default::default(),
264 stream_fade: StreamFadeTracker::default(),
265 fade_tick: None,
266 format,
267 parsed_error: None,
268 text: text.to_string(),
269 element_text: None,
270 revision: 0,
271 committed_revision: 0,
272 full_update_revision: 0,
273 rendered_index: Arc::default(),
274 range_highlights: None,
275 pending_reveal: None,
276 selection_revision: 0,
277 compatible_layout_update: false,
278 layout_text_style: None,
279 tx,
280 _parse_task,
281 _receive_task,
282 };
283 this.increment_update(&text, false, cx);
284 this
285 }
286
287 pub(crate) fn source(&self) -> SharedString {
289 self.parsed_content.document.source.clone()
290 }
291
292 pub fn selectable(mut self, selectable: bool) -> Self {
294 self.selectable = selectable;
295 self
296 }
297
298 pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
300 self.selectable = selectable;
301 cx.notify();
302 }
303
304 pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
306 self.selection_format = selection_format;
307 self
308 }
309
310 pub fn set_selection_format(
312 &mut self,
313 selection_format: SelectionFormat,
314 cx: &mut Context<Self>,
315 ) {
316 self.selection_format = selection_format;
317 cx.notify();
318 }
319
320 pub fn scrollable(mut self, scrollable: bool) -> Self {
322 self.scrollable = scrollable;
323 self
324 }
325
326 pub fn set_scrollable(&mut self, scrollable: bool, cx: &mut Context<Self>) {
328 if !scrollable {
329 self.reset_selection_and_adapter(cx);
330 }
331 self.scrollable = scrollable;
332 cx.notify();
333 }
334
335 pub fn is_clamped(&self) -> bool {
338 self.clamped
339 }
340
341 pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
348 if self.text.as_str() == text {
349 return;
350 }
351 if self.format == TextViewFormat::Markdown
355 && self.parsed_error.is_none()
356 && !self.text.is_empty()
357 && let Some(delta) = text.strip_prefix(self.text.as_str())
358 {
359 self.push_str(delta, cx);
360 return;
361 }
362 self.stream_fade.note_replace();
363
364 self.text.clear();
365 self.text.push_str(text);
366 self.parsed_error = None;
367 self.increment_update(text, false, cx);
368 }
369
370 pub(super) fn set_element_text(&mut self, text: &SharedString, cx: &mut Context<Self>) {
375 let same_string = self.element_text.as_ref().is_some_and(|current| {
376 current.as_ptr() == text.as_ptr() && current.len() == text.len()
377 });
378 if same_string && self.text.len() == text.len() {
379 return;
380 }
381 self.element_text = Some(text.clone());
382 self.set_text(text, cx);
383 }
384
385 pub fn push_str(&mut self, new_text: &str, cx: &mut Context<Self>) {
387 if new_text.is_empty() {
388 return;
389 }
390 self.stream_fade.note_extend(self.text.len());
391 self.text.push_str(new_text);
392 self.increment_update(new_text, true, cx);
393 }
394
395 pub fn motion(mut self, motion: TextViewMotion) -> Self {
397 self.set_motion(motion);
398 self
399 }
400
401 pub fn set_motion(&mut self, motion: TextViewMotion) {
403 self.stream_fade.set_motion(motion);
404 }
405
406 pub(crate) fn set_markdown_extensions(
407 &mut self,
408 markdown_extensions: Arc<MarkdownExtensions>,
409 cx: &mut Context<Self>,
410 ) {
411 if self.markdown_extensions.revision() == markdown_extensions.revision() {
412 return;
413 }
414
415 let parser_configuration_changed = !self
416 .markdown_extensions
417 .has_same_parser_configuration(&markdown_extensions);
418 self.markdown_extensions = markdown_extensions;
419 if parser_configuration_changed && self.format == TextViewFormat::Markdown {
420 let text = self.text.clone();
421 self.increment_update(&text, false, cx);
422 }
423 }
424
425 pub fn selected_text(&self) -> String {
427 self.selected_text_in(None)
428 }
429
430 pub fn selected_source_range(&self) -> Option<Range<usize>> {
441 if self.format != TextViewFormat::Markdown {
442 return None;
443 }
444 if self.select_all {
445 return Some(0..self.source().len());
446 }
447 self.parsed_content.document.selected_source_range()
448 }
449
450 fn effective_format(&self) -> SelectionFormat {
460 match self.format {
461 TextViewFormat::Markdown => self.selection_format,
462 TextViewFormat::Html => SelectionFormat::Plain,
463 }
464 }
465
466 pub(super) fn selected_text_in(&self, blocks: Option<RangeInclusive<usize>>) -> String {
473 let format = self.effective_format();
474
475 if self.select_all {
476 if format == SelectionFormat::Source {
477 return self.source().to_string();
478 }
479
480 return self.parsed_content.document.text();
481 }
482
483 if format != SelectionFormat::Source
488 && let Some(text) = &self.selected_text_override
489 {
490 return text.clone();
491 }
492
493 self.parsed_content.document.selected_text(format, blocks)
494 }
495
496 fn invalidate_measured_heights(&self) {
512 let count = self.list_state.item_count();
513 if count > 0 {
514 self.list_state.remeasure_items(0..count);
515 }
516 }
517
518 pub fn invalidate_inline_layout(&mut self, cx: &mut Context<Self>) {
524 self.preserve_inline_selection = true;
525 self.compatible_layout_update = true;
526 self.invalidate_measured_heights();
527 cx.notify();
528 }
529
530 fn increment_update(&mut self, text: &str, append: bool, cx: &mut Context<Self>) {
531 self.revision += 1;
532 if !append {
533 self.full_update_revision = self.revision;
534 self.selection_revision = self.selection_revision.wrapping_add(1);
535 }
536 let parse_synchronously = !append && text.len() <= MAX_SYNC_FULL_REPLACE_BYTES;
537 let update_options = UpdateOptions {
538 revision: self.revision,
539 append,
540 mode: if append {
541 ParseMode::Compatible
542 } else if parse_synchronously {
543 ParseMode::BaselineAck
544 } else {
545 ParseMode::Replace
546 },
547 pending_text: text.to_string(),
548 markdown_extensions: self.markdown_extensions.clone(),
549 };
550
551 if parse_synchronously {
555 match parse_content(self.format, ParsedContent::default(), &update_options) {
556 Ok(content) => {
557 self.reconcile_range_highlights(&content.document, self.revision, false);
558 self.stream_fade.record(
559 &self.parsed_content.document,
560 &content.document,
561 Instant::now(),
562 );
563 self.parsed_content = content;
564 self.parsed_error = None;
565 self.invalidate_measured_heights();
566 if !self.is_selecting {
567 self.reset_selection_and_adapter(cx);
568 }
569 }
570 Err(err) => {
571 self.stream_fade.discard_pending();
572 self.parsed_error = Some(err);
573 }
574 }
575 _ = self.tx.try_send(update_options);
579 cx.notify();
580 return;
581 }
582
583 _ = self.tx.try_send(update_options);
584 }
585
586 pub fn rendered_text(&self) -> RenderedText {
591 RenderedText::new(
592 self.entity_id,
593 self.committed_revision,
594 self.parsed_content.document.clone(),
595 self.rendered_index.clone(),
596 )
597 }
598
599 pub fn set_range_highlights(
613 &mut self,
614 highlights: impl IntoIterator<Item = RangeHighlight>,
615 cx: &mut Context<Self>,
616 ) -> Result<(), RangeHighlightError> {
617 if self.format != TextViewFormat::Markdown {
618 return Err(RangeHighlightError::Unsupported);
619 }
620 let text = self.rendered_text();
621 self.range_highlights = RangeHighlightFrame::new(&text, highlights)?.map(Arc::new);
622 cx.notify();
623 Ok(())
624 }
625
626 pub fn reveal_range(
649 &mut self,
650 range: Range<usize>,
651 cx: &mut Context<Self>,
652 ) -> Result<(), RangeHighlightError> {
653 if self.format != TextViewFormat::Markdown {
654 return Err(RangeHighlightError::Unsupported);
655 }
656 let text = self.rendered_text();
657 if text.is_empty() && range == (0..0) {
658 self.pending_reveal = None;
660 return Ok(());
661 }
662 let now = cx.background_executor().now();
663 self.pending_reveal = Some(
664 PendingReveal::new(&text, &range, now).ok_or(RangeHighlightError::InvalidRange(0))?,
665 );
666 cx.notify();
667 Ok(())
668 }
669
670 pub fn clear_range_highlights(&mut self, cx: &mut Context<Self>) {
672 if self.range_highlights.take().is_some() {
673 cx.notify();
674 }
675 }
676
677 fn reconcile_range_highlights(&mut self, new: &ParsedDocument, revision: usize, append: bool) {
685 let tail_only = append && self.full_update_revision <= self.committed_revision;
686 self.committed_revision = revision;
687 self.rendered_index = Arc::default();
688 if self.range_highlights.is_some() || self.pending_reveal.is_some() {
689 let remap = LeafRemap::new(&self.parsed_content.document, new, tail_only);
690 self.range_highlights = self
691 .range_highlights
692 .take()
693 .and_then(|highlights| highlights.remap(&remap))
694 .map(Arc::new);
695 self.pending_reveal = self
696 .pending_reveal
697 .take()
698 .and_then(|reveal| reveal.remap(&remap));
699 }
700 }
701
702 fn splice_appended_blocks(&self, new: &ParsedDocument) {
712 let old = &self.parsed_content.document.blocks;
713 let (old_count, new_count) = (old.len(), new.blocks.len());
714 if old_count == 0 || new_count <= old_count || self.list_state.item_count() != old_count {
715 return;
716 }
717
718 let unchanged = old
721 .iter()
722 .zip(new.blocks.iter())
723 .take(old_count - 1)
724 .take_while(|(old_block, new_block)| {
725 old_block
726 .span()
727 .is_some_and(|span| new_block.span() == Some(span))
728 })
729 .count();
730 self.list_state.remeasure_items(unchanged..old_count);
734 self.list_state
735 .splice(old_count..old_count, new_count - old_count);
736 }
737
738 pub(super) fn update_bounds(&mut self, bounds: Bounds<Pixels>, _cx: &mut App) {
740 self.bounds = bounds;
741 }
742
743 pub(super) fn block_ix_at(&self, content_y: Pixels) -> Option<usize> {
751 if !self.scrollable {
752 return None;
753 }
754
755 let origin = self.bounds.origin.y + self.scroll_offset().y;
756 let count = self.list_state.item_count();
757 let mut ix = self.list_state.logical_scroll_top().item_ix;
758 while ix < count {
759 let bounds = self.list_state.bounds_for_item(ix)?;
760 if content_y < bounds.bottom() - origin {
761 return Some(ix);
762 }
763 ix += 1;
764 }
765
766 count.checked_sub(1)
767 }
768
769 #[doc(hidden)]
770 pub fn bounds(&self) -> Bounds<Pixels> {
771 self.bounds
772 }
773
774 #[doc(hidden)]
775 pub fn list_state(&self) -> &ListState {
776 &self.list_state
777 }
778
779 #[doc(hidden)]
780 pub fn is_selecting(&self) -> bool {
781 self.is_selecting
782 }
783
784 #[doc(hidden)]
785 pub fn focus_handle(&self) -> &FocusHandle {
786 &self.focus_handle
787 }
788
789 pub(super) fn has_view_selection(&self) -> bool {
792 self.select_all
793 || self.multi_click_selection.is_some()
794 || self.selected_text_override.is_some()
795 }
796
797 pub(super) fn stop_auto_scroll(&mut self) {
798 self.auto_scroll.stop();
799 }
800
801 pub(super) fn reset_selection(&mut self) {
802 self.preserve_inline_selection = false;
803 self.multi_click_selection = None;
804 self.selected_text_override = None;
805 self.select_all = false;
806 self.is_selecting = false;
807 self.auto_scroll.stop();
808 self.parsed_content.document.clear_selection();
812 }
813
814 fn reset_selection_and_adapter(&mut self, cx: &mut App) {
815 self.reset_selection();
816 self.selection_adapter.set_local_selection(false, cx);
817 }
818
819 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
821 self.reset_selection_and_adapter(cx);
822 cx.notify();
823 }
824
825 pub(super) fn scroll_offset(&self) -> Point<Pixels> {
826 if self.scrollable {
827 self.list_state.scroll_px_offset_for_scrollbar()
828 } else {
829 Point::default()
830 }
831 }
832
833 pub fn select_all(&mut self, cx: &mut Context<Self>) {
835 self.multi_click_selection = None;
836 self.selected_text_override = None;
837 self.select_all = true;
838 self.is_selecting = false;
839 self.auto_scroll.stop();
840 self.selection_adapter.set_local_selection(true, cx);
841 cx.notify();
842 }
843
844 pub(crate) fn set_multi_click_selection(
845 &mut self,
846 pos: Point<Pixels>,
847 kind: TextViewMultiClickKind,
848 selected_text: String,
849 cx: &mut App,
850 ) {
851 self.preserve_inline_selection = false;
852 let scroll_offset = self.scroll_offset();
853 let pos = pos - self.bounds.origin - scroll_offset;
854 self.multi_click_selection = Some(TextViewMultiClickSelection {
855 pos,
856 kind,
857 line_bounds: None,
858 });
859 self.selected_text_override = Some(selected_text);
860 self.select_all = false;
861 self.is_selecting = false;
862 self.auto_scroll.stop();
863 self.selection_adapter.set_local_selection(true, cx);
864 }
865
866 pub(crate) fn set_multi_click_line(&mut self, bounds: Bounds<Pixels>, cx: &mut App) {
867 self.set_multi_click_selection(
868 bounds.center(),
869 TextViewMultiClickKind::Line,
870 String::new(),
871 cx,
872 );
873 self.selected_text_override = None;
874 let offset = self.bounds.origin + self.scroll_offset();
875 if let Some(selection) = self.multi_click_selection.as_mut() {
876 selection.line_bounds = Some(Bounds::new(bounds.origin - offset, bounds.size));
877 }
878 }
879
880 pub(super) fn set_auto_scroll(&mut self, delta: Option<Pixels>, cx: &mut Context<Self>) {
881 self.auto_scroll.set(delta, cx, |delta, state, cx| {
882 state.list_state.scroll_by(delta);
883 cx.notify();
884 });
885 }
886
887 pub(crate) fn selection_points(&self, cx: &App) -> Option<(Point<Pixels>, Point<Pixels>)> {
894 if !self.selectable {
895 return None;
896 }
897 self.selection_adapter.selection_points(cx)
898 }
899
900 pub(crate) fn has_selection(&self, cx: &App) -> bool {
901 self.has_view_selection() || self.selection_points(cx).is_some()
902 }
903
904 pub(super) fn on_action_select_all(
905 &mut self,
906 _: &SelectAll,
907 _: &mut Window,
908 cx: &mut Context<Self>,
909 ) {
910 if !self.selectable {
911 cx.propagate();
912 return;
913 }
914
915 self.select_all(cx);
916 }
917
918 pub(crate) fn is_selectable(&self) -> bool {
919 self.selectable
920 }
921
922 pub(crate) fn is_all_selected(&self) -> bool {
923 self.select_all
924 }
925
926 pub(crate) fn multi_click_selection(&self) -> Option<TextViewMultiClickSelection> {
927 let scroll_offset = self.scroll_offset();
928 self.multi_click_selection.map(|selection| {
929 let pos = selection.pos + scroll_offset + self.bounds.origin;
930 let line_bounds = selection.line_bounds.map(|bounds| {
931 Bounds::new(
932 bounds.origin + scroll_offset + self.bounds.origin,
933 bounds.size,
934 )
935 });
936 TextViewMultiClickSelection {
937 pos,
938 line_bounds,
939 ..selection
940 }
941 })
942 }
943}
944
945#[derive(Clone, Copy, Debug, PartialEq)]
946pub(crate) struct TextViewMultiClickSelection {
947 pub(crate) pos: Point<Pixels>,
948 pub(crate) kind: TextViewMultiClickKind,
949 pub(crate) line_bounds: Option<Bounds<Pixels>>,
950}
951
952#[derive(Clone, Copy, Debug, PartialEq, Eq)]
953pub(crate) enum TextViewMultiClickKind {
954 Word,
955 Paragraph,
956 Line,
957}
958
959impl TextViewState {
960 fn reveal_frame(
964 &mut self,
965 now: Instant,
966 window: &mut Window,
967 ) -> (Option<RevealRequest>, Option<usize>) {
968 if self.max_lines.is_some()
969 || self
970 .pending_reveal
971 .as_ref()
972 .is_some_and(|reveal| reveal.is_expired(now))
973 {
974 self.pending_reveal = None;
975 }
976 let Some(pending) = &self.pending_reveal else {
977 return (None, None);
978 };
979
980 let block_ix = pending.block_ix(&self.parsed_content.document);
981 let block_off_screen = |ix: usize| {
982 let viewport = self.list_state.viewport_bounds();
983 self.list_state.bounds_for_item(ix).is_none_or(|item| {
984 item.bottom() <= viewport.top() || item.top() >= viewport.bottom()
985 })
986 };
987 let reveal_block = block_ix.filter(|ix| {
988 self.scrollable
989 && (pending.is_block() || !pending.was_laid_out())
990 && block_off_screen(*ix)
991 });
992 let request = pending.request();
993 if pending.is_block() {
994 self.pending_reveal = None;
996 } else {
997 window.request_animation_frame();
998 }
999 (request, reveal_block)
1000 }
1001}
1002
1003impl Render for TextViewState {
1004 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1005 let typography = (window.text_style(), window.rem_size());
1006 if self
1007 .layout_text_style
1008 .as_ref()
1009 .is_some_and(|previous| previous != &typography)
1010 {
1011 self.preserve_inline_selection = true;
1015 self.compatible_layout_update = true;
1016 self.invalidate_measured_heights();
1017 }
1018 self.layout_text_style = Some(typography);
1019 let state = cx.entity();
1020 let stream_fade = self.stream_fade.frame(Instant::now(), cx.reduce_motion());
1021 if stream_fade.is_some() && self.fade_tick.is_none() {
1022 self.fade_tick = Some(cx.spawn(async move |this, cx| {
1023 cx.background_executor().timer(STREAM_FADE_TICK).await;
1024 _ = this.update(cx, |state, cx| {
1025 state.fade_tick = None;
1026 cx.notify();
1027 });
1028 }));
1029 }
1030 let (reveal, reveal_block) = self.reveal_frame(cx.background_executor().now(), window);
1031 let node_cx = NodeContext {
1033 offset: self.parsed_content.node_cx.offset,
1034 link_refs: self.parsed_content.node_cx.link_refs.clone(),
1035 style: self.text_view_style.clone(),
1036 code_block_actions: self.code_block_actions.clone(),
1037 code_block_highlighter: self.code_block_highlighter.clone(),
1038 table_actions: self.table_actions.clone(),
1039 link_click_handler: self.link_click_handler.clone(),
1040 image_source: self.image_source.clone(),
1041 markdown_extensions: self.markdown_extensions.clone(),
1042 stream_fade,
1043 range_highlights: self.range_highlights.clone(),
1044 reveal,
1045 };
1046
1047 let content = v_flex()
1048 .w_full()
1049 .when(self.max_lines.is_none(), |this| this.h_full())
1052 .map(|this| match &self.parsed_error {
1053 None => this.child(self.parsed_content.document.render_root(
1054 if self.scrollable {
1055 Some(self.list_state.clone())
1056 } else {
1057 None
1058 },
1059 &node_cx,
1060 window,
1061 cx,
1062 )),
1063 Some(err) => this.child(
1064 v_flex()
1065 .gap_1()
1066 .child("Failed to parse content")
1067 .child(err.to_string()),
1068 ),
1069 })
1070 .on_prepaint(move |bounds, window, cx| {
1071 let (
1072 size_changed,
1073 selection_involves_view,
1074 has_selection_snapshot,
1075 is_selecting,
1076 compatible_layout_update,
1077 ) = {
1078 let state = state.read(cx);
1079 (
1080 state.bounds().size != bounds.size,
1081 state.selection_adapter.is_part_of_window_selection(cx),
1082 state.selection_adapter.has_selection_snapshot(cx),
1083 state.is_selecting,
1084 state.compatible_layout_update,
1085 )
1086 };
1087 let mut revision_changed = false;
1088 state.update(cx, |state, cx| {
1089 revision_changed = state
1090 .selection_adapter
1091 .update_layout_revision(state.selection_revision, state.is_selecting);
1092 state.update_bounds(bounds, cx);
1093 state.compatible_layout_update = false;
1094 });
1095 if !is_selecting
1096 && ((size_changed && selection_involves_view && !compatible_layout_update)
1097 || (revision_changed && has_selection_snapshot))
1098 {
1099 TextSelection::clear(window, cx);
1100 }
1101 });
1102 if let Some(block_ix) = reveal_block {
1105 self.list_state.scroll_to_reveal_item(block_ix);
1106 }
1107 content
1108 }
1109}
1110
1111#[derive(Clone, PartialEq, Default)]
1112pub(crate) struct ParsedContent {
1113 pub(crate) document: ParsedDocument,
1114 pub(crate) node_cx: node::NodeContext,
1115}
1116
1117struct UpdateFuture {
1118 format: TextViewFormat,
1119 content: ParsedContent,
1120 rx: Pin<Box<Receiver<UpdateOptions>>>,
1121 tx_result: Sender<ParsedUpdate>,
1122}
1123
1124impl UpdateFuture {
1125 fn new(
1126 format: TextViewFormat,
1127 rx: Receiver<UpdateOptions>,
1128 tx_result: Sender<ParsedUpdate>,
1129 ) -> Self {
1130 Self {
1131 format,
1132 content: Default::default(),
1133 rx: Box::pin(rx),
1134 tx_result,
1135 }
1136 }
1137}
1138
1139impl Future for UpdateFuture {
1140 type Output = ();
1141
1142 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1143 loop {
1144 match self.rx.as_mut().poll_next(cx) {
1145 Poll::Ready(Some(mut options)) => {
1146 let hit_coalesce_budget =
1147 merge_pending_options(&mut options, self.rx.as_ref().get_ref());
1148
1149 let res = parse_content(self.format, self.content.clone(), &options);
1150 if let Ok(content) = &res {
1151 self.content = content.clone();
1152 }
1153 _ = self.tx_result.try_send(ParsedUpdate {
1154 revision: options.revision,
1155 full_parse: !options.append,
1156 selection_compatible: options.mode == ParseMode::Compatible,
1157 baseline_ack: options.mode == ParseMode::BaselineAck,
1158 result: res,
1159 });
1160 if hit_coalesce_budget {
1161 cx.waker().wake_by_ref();
1162 return Poll::Pending;
1163 }
1164 continue;
1165 }
1166 Poll::Ready(None) => return Poll::Ready(()),
1167 Poll::Pending => return Poll::Pending,
1168 }
1169 }
1170 }
1171}
1172
1173#[derive(Clone)]
1174struct UpdateOptions {
1175 revision: usize,
1176 pending_text: String,
1177 append: bool,
1178 mode: ParseMode,
1179 markdown_extensions: Arc<MarkdownExtensions>,
1180}
1181
1182impl UpdateOptions {
1183 fn merge(&mut self, next: UpdateOptions) {
1184 if next.append {
1185 self.pending_text.push_str(&next.pending_text);
1186 self.revision = next.revision;
1187 if self.mode != ParseMode::Replace {
1188 self.mode = ParseMode::Compatible;
1189 }
1190 } else {
1191 *self = next;
1192 }
1193 }
1194}
1195
1196struct ParsedUpdate {
1197 revision: usize,
1198 full_parse: bool,
1199 selection_compatible: bool,
1200 baseline_ack: bool,
1201 result: Result<ParsedContent, SharedString>,
1202}
1203
1204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1205enum ParseMode {
1206 BaselineAck,
1207 Replace,
1208 Compatible,
1209}
1210
1211fn merge_pending_options(options: &mut UpdateOptions, rx: &Receiver<UpdateOptions>) -> bool {
1212 let mut update_count = 1;
1213
1214 while update_count < MAX_COALESCED_UPDATES_PER_PARSE {
1215 match rx.try_recv() {
1216 Ok(next_options) => {
1217 options.merge(next_options);
1218 update_count += 1;
1219 }
1220 Err(_) => return false,
1221 }
1222 }
1223
1224 true
1225}
1226
1227fn parse_content(
1228 format: TextViewFormat,
1229 mut content: ParsedContent,
1230 options: &UpdateOptions,
1231) -> Result<ParsedContent, SharedString> {
1232 let mut node_cx = NodeContext {
1233 markdown_extensions: options.markdown_extensions.clone(),
1234 ..NodeContext::default()
1235 };
1236
1237 let last_span = options
1243 .append
1244 .then(|| {
1245 content
1246 .document
1247 .blocks
1248 .last()
1249 .and_then(|block| block.span())
1250 })
1251 .flatten();
1252
1253 let mut source = String::new();
1254 if let Some(span) = last_span {
1255 Arc::make_mut(&mut content.document.blocks).pop();
1256 node_cx.offset = span.start;
1257 source.push_str(&content.document.source[span.start..]);
1258 source.push_str(&options.pending_text);
1259 } else {
1260 if options.append {
1261 node_cx.offset = content.document.source.len();
1262 }
1263 source.push_str(&options.pending_text);
1264 }
1265
1266 let new_document = match format {
1267 TextViewFormat::Markdown => format::markdown::parse(&source, &mut node_cx),
1268 TextViewFormat::Html => format::html::parse(&source, &mut node_cx),
1269 }?;
1270
1271 if options.append {
1272 content.document.source =
1273 format!("{}{}", content.document.source, options.pending_text).into();
1274 Arc::make_mut(&mut content.document.blocks)
1275 .extend(Arc::unwrap_or_clone(new_document.blocks));
1276 } else {
1277 content.document = new_document;
1278 }
1279
1280 Ok(content)
1281}
1282
1283#[cfg(test)]
1284mod tests {
1285 use super::*;
1286 use crate::text::{
1287 MarkdownNode,
1288 node::{BlockNode, Span},
1289 };
1290 use gpui::{Entity, TestAppContext};
1291
1292 mod stream_fade {
1293 use std::{cell::Cell, ops::Range, rc::Rc, time::Duration};
1294
1295 use gpui::{Entity, TestAppContext};
1296
1297 use super::super::*;
1298 use crate::{motion::Easing, text::stream_fade::TextLeafKey};
1299
1300 const FADE: Duration = Duration::from_secs(10);
1303
1304 fn fading_state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
1305 cx.update(crate::init);
1306 let state = cx.update(|cx| {
1307 cx.new(|cx| {
1308 TextViewState::markdown(markdown, cx).motion(
1309 TextViewMotion::default()
1310 .with_stream_fade(FADE)
1311 .with_stream_fade_easing(Easing::Linear),
1312 )
1313 })
1314 });
1315 cx.run_until_parked();
1316 state
1317 }
1318
1319 fn fades(
1322 state: &Entity<TextViewState>,
1323 key: TextLeafKey,
1324 cx: &mut TestAppContext,
1325 ) -> Option<Vec<Range<usize>>> {
1326 state.update(cx, |state, _| {
1327 let frame = state.stream_fade.frame(Instant::now(), false)?;
1328 let fades = frame.fades(key)?;
1329 assert!(
1330 fades.iter().all(|(_, fade_out)| *fade_out > 0.9),
1331 "a fade sampled right after it starts is still transparent: {fades:?}"
1332 );
1333 Some(fades.iter().map(|(range, _)| range.clone()).collect())
1334 })
1335 }
1336
1337 #[gpui::test]
1338 fn push_str_fades_only_the_appended_text(cx: &mut TestAppContext) {
1339 let state = fading_state("hello", cx);
1340 state.update(cx, |state, cx| state.push_str(" world", cx));
1341 cx.run_until_parked();
1342
1343 assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1344
1345 state.update(cx, |state, _| {
1346 let later = Instant::now() + FADE + Duration::from_secs(1);
1347 assert!(state.stream_fade.frame(later, false).is_none());
1348 assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1349 });
1350 }
1351
1352 #[gpui::test]
1353 fn set_text_extending_the_text_fades_like_push_str(cx: &mut TestAppContext) {
1354 let state = fading_state("hello", cx);
1355 state.update(cx, |state, cx| state.set_text("hello world", cx));
1356 cx.run_until_parked();
1357
1358 assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1359 }
1360
1361 #[gpui::test]
1362 fn set_text_replacing_the_text_shows_it_at_once(cx: &mut TestAppContext) {
1363 let state = fading_state("hello", cx);
1364 state.update(cx, |state, cx| state.push_str(" world", cx));
1365 cx.run_until_parked();
1366 assert!(fades(&state, TextLeafKey::block(0), cx).is_some());
1367
1368 state.update(cx, |state, cx| state.set_text("other", cx));
1369 cx.run_until_parked();
1370
1371 assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1372 }
1373
1374 #[gpui::test]
1375 fn completed_markup_refades_from_the_divergence(cx: &mut TestAppContext) {
1376 let state = fading_state("text ", cx);
1379 state.update(cx, |state, cx| state.push_str("**bo", cx));
1380 cx.run_until_parked();
1381 assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![4..9]));
1382
1383 state.update(cx, |state, cx| state.push_str("ld**", cx));
1386 cx.run_until_parked();
1387 assert_eq!(
1388 fades(&state, TextLeafKey::block(0), cx),
1389 Some(vec![4..5, 5..9])
1390 );
1391 }
1392
1393 #[gpui::test]
1394 fn without_stagger_an_update_fades_as_one_chunk(cx: &mut TestAppContext) {
1395 let state = fading_state("hello", cx);
1396 state.update(cx, |state, cx| state.push_str(" one two three", cx));
1397 cx.run_until_parked();
1398
1399 assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..19]));
1400 }
1401
1402 #[gpui::test]
1403 fn words_of_one_update_start_one_after_another(cx: &mut TestAppContext) {
1404 let stagger = Duration::from_millis(100);
1405 let state = fading_state("hello", cx);
1406 state.update(cx, |state, _| {
1407 state.set_motion(
1408 TextViewMotion::default()
1409 .with_stream_fade(FADE)
1410 .with_stream_fade_stagger(stagger)
1411 .with_stream_fade_easing(Easing::Linear),
1412 )
1413 });
1414 state.update(cx, |state, cx| state.push_str(" one two three", cx));
1415 cx.run_until_parked();
1416
1417 state.update(cx, |state, _| {
1418 let frame = state
1419 .stream_fade
1420 .frame(Instant::now() + stagger * 3, false)
1421 .expect("words still fading");
1422 let fades = frame.fades(TextLeafKey::block(0)).expect("paragraph fades");
1423 let ranges: Vec<_> = fades.iter().map(|(range, _)| range.clone()).collect();
1424 assert_eq!(ranges, vec![5..10, 10..14, 14..19]);
1425 assert!(
1427 fades[0].1 < fades[1].1 && fades[1].1 < fades[2].1,
1428 "{fades:?}"
1429 );
1430 });
1431 }
1432
1433 #[gpui::test]
1434 fn a_new_paragraph_fades_as_a_whole(cx: &mut TestAppContext) {
1435 let state = fading_state("first", cx);
1436 state.update(cx, |state, cx| state.push_str("\n\nsecond", cx));
1437 cx.run_until_parked();
1438
1439 assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1440 assert_eq!(fades(&state, TextLeafKey::block(7), cx), Some(vec![0..6]));
1441 }
1442
1443 #[gpui::test]
1444 fn code_block_text_fades_by_block(cx: &mut TestAppContext) {
1445 let state = fading_state("```rs\nlet", cx);
1446 state.update(cx, |state, cx| state.push_str(" x", cx));
1447 cx.run_until_parked();
1448
1449 assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![3..5]));
1450 }
1451
1452 #[gpui::test]
1453 fn table_cells_fade_by_ordinal(cx: &mut TestAppContext) {
1454 let state = fading_state("| a | b |\n|---|---|\n| c | d", cx);
1455 state.update(cx, |state, cx| state.push_str("e |", cx));
1456 cx.run_until_parked();
1457
1458 assert_eq!(fades(&state, TextLeafKey::table_cell(0, 2), cx), None);
1459 assert_eq!(
1460 fades(&state, TextLeafKey::table_cell(0, 3), cx),
1461 Some(vec![1..2])
1462 );
1463 }
1464
1465 #[gpui::test]
1466 fn zero_duration_records_nothing(cx: &mut TestAppContext) {
1467 cx.update(crate::init);
1468 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1469 cx.run_until_parked();
1470 state.update(cx, |state, cx| state.push_str(" world", cx));
1471 cx.run_until_parked();
1472
1473 state.update(cx, |state, _| {
1474 assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1475 });
1476 }
1477
1478 #[gpui::test]
1479 fn reduced_motion_drops_the_fade(cx: &mut TestAppContext) {
1480 let state = fading_state("hello", cx);
1481 state.update(cx, |state, cx| state.push_str(" world", cx));
1482 cx.run_until_parked();
1483
1484 state.update(cx, |state, _| {
1485 assert!(state.stream_fade.frame(Instant::now(), true).is_none());
1486 assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1487 });
1488 }
1489
1490 #[gpui::test]
1491 fn a_fade_repaints_on_a_timer_until_nothing_fades(cx: &mut TestAppContext) {
1492 struct FadeRoot(Entity<TextViewState>);
1493 impl Render for FadeRoot {
1494 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1495 crate::text::TextView::new(&self.0)
1496 }
1497 }
1498
1499 let state = fading_state("hello", cx);
1500 let (_, cx) = cx.add_window_view(|_, _| FadeRoot(state.clone()));
1501 let notifies = Rc::new(Cell::new(0));
1502 let _subscription = cx.update(|_, cx| {
1503 let notifies = notifies.clone();
1504 cx.observe(&state, move |_, _| notifies.set(notifies.get() + 1))
1505 });
1506
1507 state.update(cx, |state, cx| state.push_str(" world", cx));
1508 cx.run_until_parked();
1509 cx.update(|window, cx| window.draw(cx).clear(cx));
1510 let before = notifies.get();
1511
1512 cx.executor().advance_clock(STREAM_FADE_TICK / 2);
1513 cx.run_until_parked();
1514 assert_eq!(notifies.get(), before);
1515
1516 for tick in 1..=3 {
1518 cx.executor().advance_clock(STREAM_FADE_TICK);
1519 cx.run_until_parked();
1520 assert_eq!(notifies.get(), before + tick);
1521 }
1522
1523 state.update(cx, |state, cx| state.set_text("other", cx));
1525 cx.run_until_parked();
1526 cx.executor().advance_clock(STREAM_FADE_TICK);
1527 cx.run_until_parked();
1528 let after = notifies.get();
1529 cx.executor().advance_clock(STREAM_FADE_TICK * 10);
1530 cx.run_until_parked();
1531 assert_eq!(notifies.get(), after);
1532 assert!(state.read_with(cx, |state, _| state.fade_tick.is_none()));
1533 }
1534 }
1535
1536 #[gpui::test]
1537 fn small_full_replace_parses_before_background_executor_runs(cx: &mut TestAppContext) {
1538 cx.update(crate::init);
1539 let markdown = "# ready";
1540 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
1541
1542 state.read_with(cx, |state, _| {
1543 assert_eq!(state.source().as_str(), markdown);
1544 assert_eq!(state.parsed_content.document.blocks.len(), 1);
1545 });
1546 }
1547
1548 #[gpui::test]
1549 fn large_markdown_and_html_full_replacements_wait_for_background_executor(
1550 cx: &mut TestAppContext,
1551 ) {
1552 cx.update(crate::init);
1553 let markdown = "# x\n\n".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
1554 let html = format!("<p>{}</p>", "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1));
1555 assert!(markdown.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1556 assert!(html.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1557
1558 let (markdown_state, html_state) = cx.update(|cx| {
1559 (
1560 cx.new(|cx| TextViewState::markdown(&markdown, cx)),
1561 cx.new(|cx| TextViewState::html(&html, cx)),
1562 )
1563 });
1564
1565 markdown_state.read_with(cx, |state, _| {
1566 assert_eq!(state.text.as_str(), markdown.as_str());
1567 assert!(state.source().as_str().is_empty());
1568 assert!(state.parsed_content.document.blocks.is_empty());
1569 });
1570 html_state.read_with(cx, |state, _| {
1571 assert_eq!(state.text.as_str(), html.as_str());
1572 assert!(state.source().as_str().is_empty());
1573 assert!(state.parsed_content.document.blocks.is_empty());
1574 });
1575
1576 cx.run_until_parked();
1577
1578 markdown_state.read_with(cx, |state, _| {
1579 assert_eq!(state.source().as_str(), markdown.as_str());
1580 assert!(!state.parsed_content.document.blocks.is_empty());
1581 });
1582 html_state.read_with(cx, |state, _| {
1583 assert_eq!(state.source().as_str(), html.as_str());
1584 assert!(!state.parsed_content.document.blocks.is_empty());
1585 });
1586 }
1587
1588 #[gpui::test]
1589 fn inline_source_ranges_follow_streamed_tail_reparsing(cx: &mut TestAppContext) {
1590 cx.update(crate::init);
1591 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("中文 $a$\n\n尾 $x", cx)));
1592 state.update(cx, |state, cx| {
1593 let extensions = MarkdownExtensions::default().plugin(
1594 crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(|node, _| {
1595 let markdown::mdast::Node::InlineMath(math) = node else {
1596 return None;
1597 };
1598 Some(super::super::MarkdownNode::new("formula", ()).text(math.value.clone()))
1599 }),
1600 );
1601 state.set_markdown_extensions(Arc::new(extensions), cx);
1602 });
1603 cx.run_until_parked();
1604 state.update(cx, |state, cx| state.push_str("^2$ 后", cx));
1605 cx.run_until_parked();
1606 state.read_with(cx, |state, _| {
1607 let source = "中文 $a$\n\n尾 $x^2$ 后";
1608 assert_eq!(state.source().as_str(), source);
1609 let objects: Vec<_> = state
1610 .parsed_content
1611 .document
1612 .blocks
1613 .iter()
1614 .flat_map(|block| {
1615 let super::super::node::BlockNode::Paragraph(paragraph) = block else {
1616 panic!()
1617 };
1618 paragraph
1619 .children
1620 .iter()
1621 .filter_map(|node| node.custom.as_ref())
1622 })
1623 .collect();
1624 assert_eq!(objects.len(), 2);
1625 for (object, markdown) in objects.iter().zip(["$a$", "$x^2$"]) {
1626 let start = source.find(markdown).unwrap();
1627 assert_eq!(object.source_range(), Some(start..start + markdown.len()));
1628 assert_eq!(object.as_markdown(), markdown);
1629 }
1630 });
1631 }
1632
1633 #[gpui::test]
1634 fn async_full_replace_then_push_str_preserves_complete_source(cx: &mut TestAppContext) {
1635 cx.update(crate::init);
1636 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1637 cx.run_until_parked();
1638
1639 let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
1640 let expected = format!("{replacement} tail");
1641 state.update(cx, |state, cx| {
1642 state.set_text(&replacement, cx);
1643 state.push_str(" tail", cx);
1644 });
1645 cx.run_until_parked();
1646
1647 state.read_with(cx, |state, _| {
1648 assert_eq!(state.text.as_str(), expected.as_str());
1649 assert_eq!(state.source().as_str(), expected.as_str());
1650 });
1651 }
1652
1653 #[gpui::test]
1654 fn html_push_str_keeps_earlier_blocks(cx: &mut TestAppContext) {
1655 cx.update(crate::init);
1656 let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>first</p>", cx)));
1657 cx.run_until_parked();
1658
1659 state.update(cx, |state, cx| {
1660 state.push_str("<p>second</p>", cx);
1661 });
1662 cx.run_until_parked();
1663
1664 state.read_with(cx, |state, _| {
1665 assert_eq!(state.source().as_str(), "<p>first</p><p>second</p>");
1666 let text = state
1667 .parsed_content
1668 .document
1669 .blocks
1670 .iter()
1671 .map(|block| block.text())
1672 .collect::<String>();
1673 assert!(text.contains("first"), "lost the first block: {text:?}");
1674 assert!(text.contains("second"), "lost the appended block: {text:?}");
1675 });
1676 }
1677
1678 #[gpui::test]
1679 fn element_text_of_the_same_string_is_not_compared_again(cx: &mut TestAppContext) {
1680 cx.update(crate::init);
1681 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
1682 let revision = |cx: &mut TestAppContext| state.read_with(cx, |state, _| state.revision);
1683 let text = SharedString::from("hello");
1684
1685 state.update(cx, |state, cx| state.set_element_text(&text, cx));
1686 let parsed = revision(cx);
1687 assert!(parsed > 0);
1688
1689 state.update(cx, |state, cx| state.set_element_text(&text, cx));
1692 assert_eq!(revision(cx), parsed);
1693 let equal = SharedString::from("hello".to_string());
1694 state.update(cx, |state, cx| state.set_element_text(&equal, cx));
1695 assert_eq!(revision(cx), parsed);
1696
1697 state.update(cx, |state, cx| {
1699 state.push_str(" world", cx);
1700 state.set_element_text(&equal, cx);
1701 });
1702 state.read_with(cx, |state, _| assert_eq!(state.text.as_str(), "hello"));
1703 }
1704
1705 #[gpui::test]
1706 fn set_text_then_push_str_appends_to_replaced_content(cx: &mut TestAppContext) {
1707 cx.update(crate::init);
1708 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1709 cx.run_until_parked();
1710
1711 state.update(cx, |state, cx| {
1712 state.set_text("", cx);
1713 state.push_str("new", cx);
1714 state.push_str(" text", cx);
1715 });
1716 cx.run_until_parked();
1717
1718 state.read_with(cx, |state, _| {
1719 assert_eq!(state.text.as_str(), "new text");
1720 assert_eq!(state.source().as_str(), "new text");
1721 });
1722
1723 state.update(cx, |state, cx| {
1724 state.set_text("", cx);
1725 });
1726 cx.run_until_parked();
1727
1728 state.read_with(cx, |state, _| {
1729 assert_eq!(state.text.as_str(), "");
1730 assert_eq!(state.source().as_str(), "");
1731 });
1732 }
1733
1734 #[gpui::test]
1735 fn full_parse_coalesced_with_append_preserves_new_select_all(cx: &mut TestAppContext) {
1736 cx.update(crate::init);
1737 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1738 cx.run_until_parked();
1739
1740 state.update(cx, |state, cx| {
1741 state.set_text("new", cx);
1742 state.push_str(" text", cx);
1743 state.select_all(cx);
1744 });
1745 cx.run_until_parked();
1746
1747 state.read_with(cx, |state, _| {
1748 assert!(state.select_all);
1749 assert_eq!(state.selected_text().trim(), "new text");
1750 });
1751 }
1752
1753 fn parsed_blocks(
1754 state: &Entity<TextViewState>,
1755 cx: &mut TestAppContext,
1756 ) -> Vec<(String, Option<Span>)> {
1757 state.read_with(cx, |state, _| {
1758 state
1759 .parsed_content
1760 .document
1761 .blocks
1762 .iter()
1763 .map(|block| (block.text(), block.span()))
1764 .collect()
1765 })
1766 }
1767
1768 #[gpui::test]
1769 fn set_text_extending_markdown_appends_and_keeps_selection(cx: &mut TestAppContext) {
1770 cx.update(crate::init);
1771 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1772 cx.run_until_parked();
1773 let revisions =
1774 |state: &TextViewState| (state.selection_revision, state.full_update_revision);
1775 let initial = state.read_with(cx, |state, _| revisions(state));
1776
1777 state.update(cx, |state, cx| state.set_text("hello world", cx));
1778 cx.run_until_parked();
1779 state.read_with(cx, |state, _| {
1780 assert_eq!(state.source().as_str(), "hello world");
1781 assert_eq!(revisions(state), initial);
1782 });
1783
1784 state.update(cx, |state, cx| state.set_text("hello", cx));
1785 cx.run_until_parked();
1786 state.read_with(cx, |state, _| {
1787 assert_eq!(state.source().as_str(), "hello");
1788 assert_ne!(state.selection_revision, initial.0);
1789 assert_ne!(state.full_update_revision, initial.1);
1790 });
1791 }
1792
1793 #[gpui::test]
1794 fn set_text_streaming_markdown_matches_a_full_parse(cx: &mut TestAppContext) {
1795 cx.update(crate::init);
1796 let streamed = cx.update(|cx| cx.new(|cx| TextViewState::markdown("# Title", cx)));
1797 cx.run_until_parked();
1798
1799 let filler = "word ".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
1803 let chunks = [
1804 "\n\nfirst para",
1805 "graph with `co",
1806 "de`\n\n- one\n",
1807 "- two\n\n```rust\nfn main() {",
1808 "}\n```\n\n",
1809 filler.as_str(),
1810 "\n\nlast",
1811 ];
1812 let full_update_revision = streamed.read_with(cx, |state, _| state.full_update_revision);
1813 let mut text = "# Title".to_string();
1814 for chunk in chunks {
1815 text.push_str(chunk);
1816 streamed.update(cx, |state, cx| state.set_text(&text, cx));
1817 cx.run_until_parked();
1818 }
1819 assert_eq!(
1820 streamed.read_with(cx, |state, _| state.full_update_revision),
1821 full_update_revision
1822 );
1823
1824 let parsed = cx.update(|cx| cx.new(|cx| TextViewState::markdown(&text, cx)));
1825 cx.run_until_parked();
1826
1827 assert_eq!(
1828 streamed.read_with(cx, |state, _| state.source()),
1829 parsed.read_with(cx, |state, _| state.source())
1830 );
1831 assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
1832 }
1833
1834 #[gpui::test]
1835 fn set_text_extending_html_parses_it_again(cx: &mut TestAppContext) {
1836 cx.update(crate::init);
1837 let streamed = cx.update(|cx| cx.new(|cx| TextViewState::html("<ul><li>a</li>", cx)));
1838 cx.run_until_parked();
1839
1840 let text = "<ul><li>a</li><li>b</li></ul>";
1841 streamed.update(cx, |state, cx| state.set_text(text, cx));
1842 cx.run_until_parked();
1843 assert_ne!(
1844 streamed.read_with(cx, |state, _| state.full_update_revision),
1845 0
1846 );
1847
1848 let parsed = cx.update(|cx| cx.new(|cx| TextViewState::html(text, cx)));
1849 cx.run_until_parked();
1850 assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
1851 }
1852
1853 #[gpui::test]
1854 fn set_text_extending_after_a_parse_error_parses_it_again(cx: &mut TestAppContext) {
1855 cx.update(crate::init);
1856 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1857 cx.run_until_parked();
1858
1859 let full_update_revision = state.read_with(cx, |state, _| state.full_update_revision);
1860
1861 state.update(cx, |state, cx| {
1862 state.parsed_error = Some("failed".into());
1863 state.set_text("hello world", cx);
1864 });
1865 cx.run_until_parked();
1866
1867 state.read_with(cx, |state, _| {
1868 assert!(state.parsed_error.is_none());
1869 assert_ne!(state.full_update_revision, full_update_revision);
1870 assert_eq!(state.source().as_str(), "hello world");
1871 });
1872 }
1873
1874 #[test]
1875 fn update_options_merge_keeps_latest_full_text() {
1876 let mut options = UpdateOptions {
1877 revision: 1,
1878 pending_text: "old".to_string(),
1879 append: true,
1880 mode: ParseMode::Compatible,
1881 markdown_extensions: Arc::default(),
1882 };
1883
1884 options.merge(UpdateOptions {
1885 revision: 2,
1886 pending_text: "new".to_string(),
1887 append: false,
1888 mode: ParseMode::BaselineAck,
1889 markdown_extensions: Arc::default(),
1890 });
1891 options.merge(UpdateOptions {
1892 revision: 3,
1893 pending_text: " text".to_string(),
1894 append: true,
1895 mode: ParseMode::Compatible,
1896 markdown_extensions: Arc::default(),
1897 });
1898
1899 assert_eq!(options.revision, 3);
1900 assert_eq!(options.pending_text, "new text");
1901 assert!(!options.append);
1902 }
1903
1904 #[test]
1905 fn append_merged_into_async_replace_remains_a_replacement() {
1906 let mut options = UpdateOptions {
1907 revision: 1,
1908 pending_text: "new".to_string(),
1909 append: false,
1910 mode: ParseMode::Replace,
1911 markdown_extensions: Arc::default(),
1912 };
1913
1914 options.merge(UpdateOptions {
1915 revision: 2,
1916 pending_text: " text".to_string(),
1917 append: true,
1918 mode: ParseMode::Compatible,
1919 markdown_extensions: Arc::default(),
1920 });
1921
1922 assert_eq!(options.revision, 2);
1923 assert_eq!(options.pending_text, "new text");
1924 assert!(!options.append);
1925 assert_eq!(options.mode, ParseMode::Replace);
1926 }
1927
1928 #[test]
1929 fn update_future_yields_before_coalescing_all_queued_updates() {
1930 let (tx, rx) = unbounded::<UpdateOptions>();
1931 let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
1932 let total_updates = 128;
1933
1934 for revision in 1..=total_updates {
1935 tx.try_send(UpdateOptions {
1936 revision,
1937 pending_text: format!("{revision}\n"),
1938 append: revision != 1,
1939 mode: if revision == 1 {
1940 ParseMode::BaselineAck
1941 } else {
1942 ParseMode::Compatible
1943 },
1944 markdown_extensions: Arc::default(),
1945 })
1946 .unwrap();
1947 }
1948
1949 let mut future = Box::pin(UpdateFuture::new(TextViewFormat::Markdown, rx, tx_result));
1950 let waker = futures::task::noop_waker();
1951 let mut task_cx = std::task::Context::from_waker(&waker);
1952
1953 assert!(matches!(
1954 std::future::Future::poll(future.as_mut(), &mut task_cx),
1955 Poll::Pending
1956 ));
1957 let parsed_update = rx_result.try_recv().expect("parse result");
1958
1959 assert!(
1960 parsed_update.revision < total_updates,
1961 "single poll coalesced every queued update through revision {}",
1962 parsed_update.revision
1963 );
1964
1965 assert!(matches!(
1966 std::future::Future::poll(future.as_mut(), &mut task_cx),
1967 Poll::Pending
1968 ));
1969 let parsed_update = rx_result.try_recv().expect("next parse result");
1970 assert_eq!(parsed_update.revision, total_updates);
1971 }
1972
1973 #[gpui::test]
1974 fn select_all_returns_rendered_text(cx: &mut TestAppContext) {
1975 cx.update(crate::init);
1976 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("**quick** value", cx)));
1977 cx.run_until_parked();
1978
1979 state.update(cx, |state, cx| {
1980 state.select_all(cx);
1981 });
1982
1983 state.read_with(cx, |state, _| {
1984 assert!(state.has_view_selection());
1985 assert_eq!(state.selected_text().trim(), "quick value");
1986 });
1987
1988 state.update(cx, |state, cx| {
1989 state.clear_selection(cx);
1990 });
1991
1992 state.read_with(cx, |state, _| {
1993 assert!(!state.has_view_selection());
1994 assert_eq!(state.selected_text(), "");
1995 });
1996 }
1997
1998 #[gpui::test]
1999 fn select_all_in_source_format_returns_source(cx: &mut TestAppContext) {
2000 cx.update(crate::init);
2001 let markdown = "**quick** value";
2002 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2003 cx.run_until_parked();
2004
2005 state.update(cx, |state, cx| state.select_all(cx));
2006
2007 state.read_with(cx, |state, _| {
2009 assert_eq!(state.selected_text().trim(), "quick value");
2010 });
2011
2012 state.update(cx, |state, cx| {
2013 state.set_selection_format(SelectionFormat::Source, cx)
2014 });
2015
2016 state.read_with(cx, |state, _| {
2018 assert_eq!(state.selected_text().trim(), markdown);
2019 });
2020 }
2021
2022 #[gpui::test]
2023 fn selected_source_range_returns_full_markdown_source_for_select_all(cx: &mut TestAppContext) {
2024 cx.update(crate::init);
2025 let markdown = "**quick** value";
2026 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2027 cx.run_until_parked();
2028
2029 state.update(cx, |state, cx| state.select_all(cx));
2030
2031 state.read_with(cx, |state, _| {
2032 assert_eq!(state.selected_source_range(), Some(0..markdown.len()));
2033 });
2034 }
2035
2036 #[gpui::test]
2037 fn selected_source_range_returns_none_for_html(cx: &mut TestAppContext) {
2038 cx.update(crate::init);
2039 let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<b>quick</b>", cx)));
2040 cx.run_until_parked();
2041
2042 state.update(cx, |state, cx| state.select_all(cx));
2043
2044 state.read_with(cx, |state, _| {
2045 assert_eq!(state.selected_source_range(), None);
2046 });
2047 }
2048
2049 #[test]
2050 fn selected_source_range_keeps_global_offsets_after_incremental_tail_parse() {
2051 let options = UpdateOptions {
2052 revision: 1,
2053 pending_text: "first\n\nsecond".to_string(),
2054 append: false,
2055 mode: ParseMode::Replace,
2056 markdown_extensions: Arc::default(),
2057 };
2058 let content = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2059 .expect("initial parse");
2060 let content = parse_content(
2061 TextViewFormat::Markdown,
2062 content,
2063 &UpdateOptions {
2064 revision: 2,
2065 pending_text: "\n\n**écho**".to_string(),
2066 append: true,
2067 mode: ParseMode::Compatible,
2068 markdown_extensions: Arc::default(),
2069 },
2070 )
2071 .expect("incremental parse");
2072 let BlockNode::Paragraph(paragraph) = &content.document.blocks[2] else {
2073 panic!("expected appended paragraph");
2074 };
2075 let mut state = paragraph.state.lock().unwrap();
2076 state.set_text(paragraph.text().into());
2077 state.selection = Some((0.."écho".len()).into());
2078 drop(state);
2079
2080 assert_eq!(content.document.selected_source_range(), Some(17..22));
2081 }
2082
2083 #[test]
2084 fn streamed_ordered_list_continuation_preserves_start() {
2085 let initial = parse_content(
2086 TextViewFormat::Markdown,
2087 ParsedContent::default(),
2088 &UpdateOptions {
2089 revision: 1,
2090 pending_text: "3. three".to_string(),
2091 append: false,
2092 mode: ParseMode::Replace,
2093 markdown_extensions: Arc::default(),
2094 },
2095 )
2096 .expect("initial list parse");
2097 let continued = parse_content(
2098 TextViewFormat::Markdown,
2099 initial,
2100 &UpdateOptions {
2101 revision: 2,
2102 pending_text: "\n4. four".to_string(),
2103 append: true,
2104 mode: ParseMode::Compatible,
2105 markdown_extensions: Arc::default(),
2106 },
2107 )
2108 .expect("streamed list continuation parse");
2109
2110 let BlockNode::List {
2111 start, children, ..
2112 } = &continued.document.blocks[0]
2113 else {
2114 panic!("expected streamed ordered list");
2115 };
2116 assert_eq!(*start, Some(3));
2117 assert_eq!(children.len(), 2);
2118 }
2119
2120 #[gpui::test]
2121 fn parser_revision_reparses_same_name_inline_configuration(cx: &mut TestAppContext) {
2122 cx.update(crate::init);
2123 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("@member", cx)));
2124 for (revision, label) in [(1, "Alice"), (2, "Bob")] {
2125 let extensions = MarkdownExtensions::default()
2126 .parser_revision(revision)
2127 .plugin(
2128 crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2129 move |node, _| {
2130 matches!(node, markdown::mdast::Node::Text(_))
2131 .then(|| MarkdownNode::new("mention", label).text(label))
2132 },
2133 ),
2134 );
2135 state.update(cx, |state, cx| {
2136 state.set_markdown_extensions(Arc::new(extensions), cx)
2137 });
2138 cx.run_until_parked();
2139 state.read_with(cx, |state, _| {
2140 let node::BlockNode::Paragraph(paragraph) =
2141 &state.parsed_content.document.blocks[0]
2142 else {
2143 panic!()
2144 };
2145 assert_eq!(
2146 paragraph.children[0].custom.as_ref().unwrap().as_text(),
2147 label
2148 );
2149 });
2150 }
2151 }
2152
2153 #[gpui::test]
2154 fn set_markdown_extensions_reparses_existing_text(cx: &mut TestAppContext) {
2155 cx.update(crate::init);
2156 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("$TSLA.US", cx)));
2157 cx.run_until_parked();
2158
2159 let extensions = MarkdownExtensions::default().block_parser(|node, cx| {
2160 let markdown::mdast::Node::Paragraph(paragraph) = node else {
2161 return None;
2162 };
2163 let [markdown::mdast::Node::Text(text)] = paragraph.children.as_slice() else {
2164 return None;
2165 };
2166 let symbol = text.value.strip_prefix('$')?.to_string();
2167 let node_text = format!("${symbol}");
2168
2169 Some(
2170 MarkdownNode::new("ticker", symbol)
2171 .text(node_text)
2172 .markdown(cx.node_source(node).unwrap_or_default()),
2173 )
2174 });
2175
2176 state.update(cx, |state, cx| {
2177 state.set_markdown_extensions(Arc::new(extensions), cx);
2178 });
2179 cx.run_until_parked();
2180
2181 state.read_with(cx, |state, _| {
2182 let node::BlockNode::Custom(node) = &state.parsed_content.document.blocks[0] else {
2183 panic!("expected custom markdown node");
2184 };
2185 assert_eq!(node.name(), "ticker");
2186 assert_eq!(node.data::<String>().map(String::as_str), Some("TSLA.US"));
2187 });
2188 }
2189
2190 mod range_highlights {
2191 use std::ops::Range;
2192
2193 use gpui::{Entity, TestAppContext};
2194
2195 use super::super::*;
2196 use crate::text::stream_fade::TextLeafKey;
2197
2198 fn state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
2199 cx.update(crate::init);
2200 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2201 cx.run_until_parked();
2202 state
2203 }
2204
2205 fn highlight(range: Range<usize>) -> RangeHighlight {
2206 RangeHighlight::new(range, gpui::hsla(0.15, 1., 0.5, 0.4))
2207 }
2208
2209 fn set(
2211 state: &Entity<TextViewState>,
2212 ranges: impl IntoIterator<Item = Range<usize>>,
2213 cx: &mut TestAppContext,
2214 ) -> Result<(), RangeHighlightError> {
2215 state.update(cx, |state, cx| {
2216 state.set_range_highlights(ranges.into_iter().map(highlight), cx)
2217 })
2218 }
2219
2220 fn painted(
2222 state: &Entity<TextViewState>,
2223 key: TextLeafKey,
2224 cx: &mut TestAppContext,
2225 ) -> Vec<Range<usize>> {
2226 state.read_with(cx, |state, _| {
2227 state.range_highlights.as_ref().map_or(Vec::new(), |frame| {
2228 frame
2229 .backgrounds(key)
2230 .iter()
2231 .map(|(range, _)| range.clone())
2232 .collect()
2233 })
2234 })
2235 }
2236
2237 fn has_highlights(state: &Entity<TextViewState>, cx: &mut TestAppContext) -> bool {
2238 state.read_with(cx, |state, _| state.range_highlights.is_some())
2239 }
2240
2241 #[gpui::test]
2242 fn rendered_text_is_the_plain_copy_text(cx: &mut TestAppContext) {
2243 let state = state(
2244 "# Title\n\nhello **world** \\*\n\n- item\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```",
2245 cx,
2246 );
2247 state.read_with(cx, |state, _| {
2248 assert_eq!(
2249 state.rendered_text().as_str(),
2250 "Title\nhello world *\nitem\na b\nc d\n\nlet x\n"
2251 );
2252 });
2253 }
2254
2255 #[gpui::test]
2256 fn a_match_across_marks_paints_in_its_paragraph(cx: &mut TestAppContext) {
2257 let state = state("hello **world**", cx);
2258 set(&state, [0.."hello world".len()], cx).unwrap();
2259 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..11]);
2260 }
2261
2262 #[gpui::test]
2263 fn repeated_text_maps_to_the_occurrence_addressed(cx: &mut TestAppContext) {
2264 let state = state("foo\n\nfoo", cx);
2265 let second = state.read_with(cx, |state, _| {
2266 state.rendered_text().as_str().rfind("foo").unwrap()
2267 });
2268 set(&state, [second..second + 3], cx).unwrap();
2269 assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2270 assert_eq!(painted(&state, TextLeafKey::block(5), cx), [0..3]);
2271 }
2272
2273 #[gpui::test]
2274 fn a_range_across_blocks_skips_the_separator(cx: &mut TestAppContext) {
2275 let state = state("ab\n\ncd", cx);
2276 set(&state, [1..4], cx).unwrap();
2278 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [1..2]);
2279 assert_eq!(painted(&state, TextLeafKey::block(4), cx), [0..1]);
2280 }
2281
2282 #[gpui::test]
2283 fn table_cells_and_code_blocks_are_leaves(cx: &mut TestAppContext) {
2284 let state = state("| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```", cx);
2285 set(&state, [0..3, 6..7, 9..12], cx).unwrap();
2287 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2288 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 1), cx), [0..1]);
2289 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 3), cx), [0..1]);
2290 let code_start = "| a | b |\n|---|---|\n| c | d |\n\n".len();
2291 assert_eq!(painted(&state, TextLeafKey::block(code_start), cx), [0..3]);
2292 }
2293
2294 #[gpui::test]
2295 fn invalid_ranges_reject_the_whole_set(cx: &mut TestAppContext) {
2296 let state = state("中文\n\nab", cx);
2297 set(&state, [0.."中".len()], cx).unwrap();
2299 let invalid = [Range { start: 6, end: 3 }, 0..1, 0..100];
2300 for range in invalid {
2301 assert_eq!(
2302 set(&state, [0..3, range.clone()], cx),
2303 Err(RangeHighlightError::InvalidRange(1)),
2304 "{range:?}"
2305 );
2306 }
2307 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2309 }
2310
2311 #[gpui::test]
2312 fn text_outside_every_block_is_left_unpainted(cx: &mut TestAppContext) {
2313 let source = "foo one\n\n<div>foo two</div>\n\n| foo | x |\n|---|---|\n\nfoo three";
2314 let state = state(source, cx);
2315 let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
2316 let ranges = text
2320 .match_indices("foo")
2321 .chain(text.match_indices(' '))
2322 .map(|(start, found)| start..start + found.len())
2323 .chain([3..3, 7..8])
2324 .collect::<Vec<_>>();
2325 set(&state, ranges, cx).unwrap();
2326 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3, 3..4]);
2327 let table = source.find("| foo").unwrap();
2328 assert_eq!(
2329 painted(&state, TextLeafKey::table_cell(table, 0), cx),
2330 [0..3]
2331 );
2332 let last = source.find("foo three").unwrap();
2333 assert_eq!(painted(&state, TextLeafKey::block(last), cx), [0..3, 3..4]);
2334 }
2335
2336 #[gpui::test]
2337 fn a_later_highlight_paints_over_an_earlier_one(cx: &mut TestAppContext) {
2338 let state = state("abcdef", cx);
2339 set(&state, [0..6, 2..3], cx).unwrap();
2340 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..6, 2..3]);
2341 }
2342
2343 #[gpui::test]
2344 fn html_text_is_unsupported(cx: &mut TestAppContext) {
2345 let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
2346 cx.run_until_parked();
2347 html.update(cx, |html, cx| {
2348 assert_eq!(
2349 html.set_range_highlights([highlight(0..3)], cx),
2350 Err(RangeHighlightError::Unsupported)
2351 );
2352 });
2353 }
2354
2355 #[gpui::test]
2356 fn inline_objects_are_skipped(cx: &mut TestAppContext) {
2357 let state = state("x $a$ y", cx);
2358 state.update(cx, |state, cx| {
2359 let extensions = MarkdownExtensions::default().plugin(
2360 crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2361 |node, _| {
2362 let markdown::mdast::Node::InlineMath(math) = node else {
2363 return None;
2364 };
2365 Some(
2366 crate::text::MarkdownNode::new("formula", ())
2367 .text(math.value.clone()),
2368 )
2369 },
2370 ),
2371 );
2372 state.set_markdown_extensions(Arc::new(extensions), cx);
2373 });
2374 cx.run_until_parked();
2375 set(&state, [2..3], cx).unwrap();
2377 assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2378 set(&state, [0..5], cx).unwrap();
2379 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..2, 3..5]);
2380 }
2381
2382 #[gpui::test]
2383 fn push_str_keeps_earlier_blocks_and_clips_the_changed_tail(cx: &mut TestAppContext) {
2384 let state = state("first\n\na **b", cx);
2385 set(&state, [0..5, 6..11], cx).unwrap();
2387
2388 state.update(cx, |state, cx| state.push_str("c**", cx));
2390 cx.run_until_parked();
2391
2392 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2393 assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..2]);
2394 }
2395
2396 #[gpui::test]
2397 fn push_str_keeps_a_block_whose_text_is_unchanged(cx: &mut TestAppContext) {
2398 let state = state("first\n\nsecond", cx);
2399 set(&state, [6..12], cx).unwrap();
2400 state.update(cx, |state, cx| state.push_str("\n===", cx));
2403 cx.run_until_parked();
2404 assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..6]);
2405 }
2406
2407 #[gpui::test]
2408 fn push_str_drops_highlights_of_a_leaf_that_is_gone(cx: &mut TestAppContext) {
2409 let state = state("first\n\n| a |", cx);
2410 set(&state, [0..5, 6..11], cx).unwrap();
2411 state.update(cx, |state, cx| state.push_str("\n|---|", cx));
2414 cx.run_until_parked();
2415 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2416 assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2417 assert!(painted(&state, TextLeafKey::table_cell(7, 0), cx).is_empty());
2418 }
2419
2420 #[gpui::test]
2421 fn replacing_text_drops_highlights_only_where_it_changed(cx: &mut TestAppContext) {
2422 let state = state("first\n\nsecond", cx);
2423 set(&state, [0..5, 6..12], cx).unwrap();
2424 state.update(cx, |state, cx| state.set_text("first\n\nchanged", cx));
2425 cx.run_until_parked();
2426 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2427 assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2428
2429 let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2430 state.update(cx, |state, cx| state.set_text(&large, cx));
2431 cx.run_until_parked();
2432 assert!(!has_highlights(&state, cx));
2433 }
2434
2435 #[gpui::test]
2436 fn a_highlight_follows_its_block_past_an_earlier_edit(cx: &mut TestAppContext) {
2437 let state = state("foo\n\nbar\n\nbar", cx);
2438 set(&state, [4..7], cx).unwrap();
2440 state.update(cx, |state, cx| state.set_text("bar\n\nbar", cx));
2442 cx.run_until_parked();
2443 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2444 assert!(painted(&state, TextLeafKey::block(5), cx).is_empty());
2445
2446 let state = self::state("ERROR a\n\nERROR b\n\nERROR c", cx);
2447 set(&state, [8..15], cx).unwrap();
2448 state.update(cx, |state, cx| state.set_text("ERROR b\n\nERROR c", cx));
2449 cx.run_until_parked();
2450 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..7]);
2451 assert!(painted(&state, TextLeafKey::block(9), cx).is_empty());
2452 }
2453
2454 #[gpui::test]
2455 fn appending_a_copy_of_the_last_block_keeps_the_highlight_on_it(cx: &mut TestAppContext) {
2456 let state = state("a\n\nfoo", cx);
2457 set(&state, [2..5], cx).unwrap();
2459 state.update(cx, |state, cx| state.set_text("a\n\nfoo\n\nfoo", cx));
2460 cx.run_until_parked();
2461 assert_eq!(painted(&state, TextLeafKey::block(3), cx), [0..3]);
2462 assert!(painted(&state, TextLeafKey::block(8), cx).is_empty());
2463 }
2464
2465 #[gpui::test]
2466 fn deleting_a_table_row_drops_highlights_in_the_rows_it_moves(cx: &mut TestAppContext) {
2467 let table = "| a | b |\n|---|---|\n| x | 1 |\n| x | 2 |";
2468 let without_middle_row = "| a | b |\n|---|---|\n| x | 2 |";
2469 for ranges in [vec![8..9, 10..11], vec![4..5]] {
2472 let state = state(table, cx);
2473 set(&state, [0..1].into_iter().chain(ranges), cx).unwrap();
2474 state.update(cx, |state, cx| state.set_text(without_middle_row, cx));
2475 cx.run_until_parked();
2476 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2477 for cell in 1..4 {
2478 assert!(
2479 painted(&state, TextLeafKey::table_cell(0, cell), cx).is_empty(),
2480 "cell {cell}"
2481 );
2482 }
2483 }
2484 }
2485
2486 #[gpui::test]
2487 fn streaming_table_rows_keeps_the_highlights_of_earlier_rows(cx: &mut TestAppContext) {
2488 let state = state("| a | b |\n|---|---|\n| x | 1 |", cx);
2489 set(&state, [0..1, 4..5], cx).unwrap();
2491 state.update(cx, |state, cx| {
2492 state.set_text("| a | b |\n|---|---|\n| x | 1 |\n| y | 2 |", cx)
2493 });
2494 cx.run_until_parked();
2495 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2496 assert_eq!(painted(&state, TextLeafKey::table_cell(0, 2), cx), [0..1]);
2497 }
2498
2499 #[gpui::test]
2500 fn an_edit_in_an_earlier_block_keeps_later_highlights(cx: &mut TestAppContext) {
2501 let state = state("one\n\ntwo", cx);
2502 set(&state, [0..3, 4..7], cx).unwrap();
2503 state.update(cx, |state, cx| state.set_text("one!\n\ntwo", cx));
2504 cx.run_until_parked();
2505 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2506 assert_eq!(painted(&state, TextLeafKey::block(6), cx), [0..3]);
2507 }
2508
2509 #[gpui::test]
2510 fn an_append_after_a_full_update_compares_every_block(cx: &mut TestAppContext) {
2511 let state = state("first\n\nsecond", cx);
2512 set(&state, [0..5], cx).unwrap();
2513 let options = UpdateOptions {
2516 revision: 0,
2517 pending_text: "FIRST\n\nsecond".to_string(),
2518 append: false,
2519 mode: ParseMode::Replace,
2520 markdown_extensions: Arc::default(),
2521 };
2522 let new = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2523 .unwrap()
2524 .document;
2525 state.update(cx, |state, _| {
2526 state.full_update_revision = state.committed_revision + 1;
2527 let revision = state.committed_revision + 2;
2528 state.reconcile_range_highlights(&new, revision, true);
2529 });
2530 assert!(!has_highlights(&state, cx));
2531 }
2532
2533 #[gpui::test]
2534 fn streaming_through_set_text_keeps_highlights(cx: &mut TestAppContext) {
2535 let state = state("first\n\nsec", cx);
2536 set(&state, [0..5, 6..9], cx).unwrap();
2538 state.update(cx, |state, cx| state.set_text("first\n\nsecond", cx));
2539 cx.run_until_parked();
2540 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2541 assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..3]);
2542 }
2543
2544 #[gpui::test]
2545 fn a_full_parse_merged_with_an_append_compares_every_block(cx: &mut TestAppContext) {
2546 let state = state("", cx);
2547 state.update(cx, |state, cx| {
2551 state.set_text("[foo] and some text\n\nmore", cx);
2552 let text = state.rendered_text();
2553 let some = text.as_str().find("some").unwrap();
2554 state
2555 .set_range_highlights([highlight(some..some + 4)], cx)
2556 .unwrap();
2557 state.push_str("\n\n[foo]: https://example.com", cx);
2558 });
2559 cx.run_until_parked();
2560 state.read_with(cx, |state, _| {
2561 assert!(state.rendered_text().as_str().starts_with("foo and some"));
2562 });
2563 assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2564 }
2565
2566 #[gpui::test]
2567 fn a_full_update_before_an_append_drops_replaced_highlights(cx: &mut TestAppContext) {
2568 let state = state("first", cx);
2569 set(&state, [0..5], cx).unwrap();
2570 let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2571 state.update(cx, |state, cx| {
2572 state.set_text(&large, cx);
2573 state.push_str(" tail", cx);
2574 });
2575 cx.run_until_parked();
2576 assert!(!has_highlights(&state, cx));
2577 }
2578
2579 #[gpui::test]
2580 fn reparsing_unchanged_text_keeps_highlights(cx: &mut TestAppContext) {
2581 let state = state("first", cx);
2582 set(&state, [0..5], cx).unwrap();
2583 state.update(cx, |state, cx| {
2584 state.set_markdown_extensions(
2585 Arc::new(MarkdownExtensions::default().parser_revision(1)),
2586 cx,
2587 )
2588 });
2589 cx.run_until_parked();
2590 assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2591 }
2592
2593 pub(super) struct Root {
2594 pub(super) state: Entity<TextViewState>,
2595 }
2596
2597 impl Render for Root {
2598 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2599 gpui::div()
2600 .w(px(120.))
2601 .child(crate::text::TextView::new(&self.state).selectable(true))
2602 }
2603 }
2604
2605 #[gpui::test]
2606 fn highlights_paint_across_inline_code_tables_and_code_blocks(cx: &mut TestAppContext) {
2607 cx.update(crate::init);
2608 let markdown = "wrapping text with `inline code` and a [link](https://x.y) \
2609 that wraps\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x = 1;\n```";
2610 let (root, cx) = cx.add_window_view(|_, cx| Root {
2611 state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
2612 });
2613 cx.run_until_parked();
2614 let state = root.read_with(cx, |root, _| root.state.clone());
2615 let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
2616 let code = text.find("code").unwrap();
2617 let len = text.len();
2618 let ranges = [code..code + 2]
2620 .into_iter()
2621 .chain(text.char_indices().map(|(ix, c)| ix..ix + c.len_utf8()))
2622 .chain([0..len])
2623 .filter(|range| !text[range.clone()].trim().is_empty());
2624 state.update(cx, |state, cx| {
2625 state
2626 .set_range_highlights(ranges.map(highlight), cx)
2627 .unwrap();
2628 });
2629 cx.update(|window, cx| window.draw(cx).clear(cx));
2630 assert_eq!(
2631 painted(&state, TextLeafKey::block(0), cx)[0],
2632 code..code + 2
2633 );
2634 }
2635
2636 #[gpui::test]
2637 fn clear_range_highlights_removes_them(cx: &mut TestAppContext) {
2638 let state = state("first", cx);
2639 set(&state, [0..5], cx).unwrap();
2640 state.update(cx, |state, cx| state.clear_range_highlights(cx));
2641 assert!(!has_highlights(&state, cx));
2642 }
2643 }
2644
2645 mod reveal_range {
2646 use gpui::{
2647 Entity, InteractiveElement as _, ListAlignment, ListState, ScrollHandle,
2648 StatefulInteractiveElement as _, TestAppContext, VisualTestContext, div, list,
2649 };
2650
2651 use super::super::*;
2652 use crate::text::TextView;
2653
2654 #[derive(Clone)]
2656 enum Container {
2657 Scrollable,
2659 List(ListState),
2661 Div(ScrollHandle),
2664 Clamped(ListState),
2666 Fixed,
2668 }
2669
2670 struct Root {
2671 state: Entity<TextViewState>,
2672 container: Container,
2673 }
2674
2675 impl Render for Root {
2676 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2677 let state = self.state.clone();
2678 let frame = div().w(px(200.)).h(px(100.));
2679 let row = |list_state: &ListState, clamp: bool| {
2680 let state = state.clone();
2681 list(list_state.clone(), move |ix, _, _| match ix {
2682 0 => div().h(px(40.)).into_any_element(),
2683 _ => TextView::new(&state)
2684 .when(clamp, |view| view.max_lines(2))
2685 .into_any_element(),
2686 })
2687 .size_full()
2688 };
2689 match &self.container {
2690 Container::Scrollable => frame
2691 .child(TextView::new(&state).scrollable(true))
2692 .into_any_element(),
2693 Container::List(list_state) => {
2694 frame.child(row(list_state, false)).into_any_element()
2695 }
2696 Container::Clamped(list_state) => {
2697 frame.child(row(list_state, true)).into_any_element()
2698 }
2699 Container::Div(handle) => {
2700 let scroll = handle.clone();
2701 frame
2702 .child(
2703 div()
2704 .id("scroll")
2705 .size_full()
2706 .overflow_y_scroll()
2707 .track_scroll(handle)
2708 .child(TextView::new(&state).on_reveal(move |line, _, _| {
2709 let viewport = scroll.bounds();
2710 let mut offset = scroll.offset();
2711 if line.bottom() > viewport.bottom() {
2712 offset.y -= line.bottom() - viewport.bottom();
2713 } else if line.top() < viewport.top() {
2714 offset.y += viewport.top() - line.top();
2715 }
2716 scroll.set_offset(offset);
2717 })),
2718 )
2719 .into_any_element()
2720 }
2721 Container::Fixed => frame.child(TextView::new(&state)).into_any_element(),
2722 }
2723 }
2724 }
2725
2726 fn window<'a>(
2727 markdown: &str,
2728 container: Container,
2729 cx: &'a mut TestAppContext,
2730 ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
2731 crate::test_text_system::install(cx);
2732 cx.update(crate::init);
2733 let (root, cx) = cx.add_window_view(|_, cx| Root {
2734 state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
2735 container,
2736 });
2737 cx.simulate_resize(gpui::size(px(200.), px(100.)));
2739 cx.run_until_parked();
2740 draw(cx);
2741 let state = root.read_with(cx, |root, _| root.state.clone());
2742 (state, cx)
2743 }
2744
2745 fn draw(cx: &mut VisualTestContext) {
2746 cx.update(|window, cx| window.draw(cx).clear(cx));
2747 }
2748
2749 fn request(
2752 state: &Entity<TextViewState>,
2753 needle: &str,
2754 cx: &mut VisualTestContext,
2755 then: impl FnOnce(&mut TextViewState, &mut Context<TextViewState>),
2756 ) {
2757 state.update(cx, |state, cx| {
2758 let text = state.rendered_text();
2759 let start = text.as_str().find(needle).unwrap();
2760 state.reveal_range(start..start + needle.len(), cx).unwrap();
2761 then(state, cx);
2762 });
2763 }
2764
2765 fn reveal(state: &Entity<TextViewState>, needle: &str, cx: &mut VisualTestContext) {
2767 request(state, needle, cx, |_, _| {});
2768 for _ in 0..3 {
2769 draw(cx);
2770 }
2771 }
2772
2773 fn is_pending(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> bool {
2774 state.read_with(cx, |state, _| state.pending_reveal.is_some())
2775 }
2776
2777 fn scroll_top(
2778 state: &Entity<TextViewState>,
2779 cx: &mut VisualTestContext,
2780 ) -> gpui::ListOffset {
2781 state.read_with(cx, |state, _| state.list_state.logical_scroll_top())
2782 }
2783
2784 fn paragraphs(count: usize) -> String {
2785 (0..count)
2786 .map(|ix| format!("paragraph {ix}"))
2787 .collect::<Vec<_>>()
2788 .join("\n\n")
2789 }
2790
2791 fn words(count: usize) -> String {
2792 (0..count)
2793 .map(|ix| format!("w{ix}"))
2794 .collect::<Vec<_>>()
2795 .join(" ")
2796 }
2797
2798 #[gpui::test]
2799 fn a_scrollable_view_scrolls_to_an_offscreen_block(cx: &mut TestAppContext) {
2800 let (state, cx) = window(¶graphs(200), Container::Scrollable, cx);
2801 reveal(&state, "paragraph 150", cx);
2802 assert!(!is_pending(&state, cx));
2803 let top = scroll_top(&state, cx);
2804 assert!((140..=150).contains(&top.item_ix), "{top:?}");
2805
2806 reveal(&state, "paragraph 3", cx);
2807 assert!(!is_pending(&state, cx));
2808 assert!(scroll_top(&state, cx).item_ix <= 3);
2809 }
2810
2811 #[gpui::test]
2812 fn an_append_adding_blocks_keeps_the_scroll_position(cx: &mut TestAppContext) {
2813 let (state, cx) = window(¶graphs(200), Container::Scrollable, cx);
2814 reveal(&state, "paragraph 100", cx);
2815 let top = scroll_top(&state, cx);
2816 assert!(top.item_ix > 0, "{top:?}");
2817
2818 state.update(cx, |state, cx| state.push_str("\n\nparagraph 200", cx));
2819 cx.run_until_parked();
2820 draw(cx);
2821
2822 state.read_with(cx, |state, _| {
2823 assert_eq!(state.list_state.item_count(), 201);
2824 });
2825 assert_unmoved(&state, top, cx);
2826 }
2827
2828 #[gpui::test]
2829 fn a_scrollable_view_scrolls_to_a_line_inside_a_long_paragraph(cx: &mut TestAppContext) {
2830 let (state, cx) = window(&words(400), Container::Scrollable, cx);
2831 reveal(&state, "w390", cx);
2832 assert!(!is_pending(&state, cx));
2833 let top = scroll_top(&state, cx);
2834 assert_eq!(top.item_ix, 0);
2835 assert!(top.offset_in_item > px(100.), "{top:?}");
2836 }
2837
2838 #[gpui::test]
2839 fn revealing_a_visible_line_does_not_scroll(cx: &mut TestAppContext) {
2840 let (state, cx) = window(&words(400), Container::Scrollable, cx);
2841 reveal(&state, "w200", cx);
2842 let top = scroll_top(&state, cx);
2843 assert!(top.offset_in_item > px(0.), "{top:?}");
2844 for word in ["w199", "w198", "w197", "w196"] {
2845 reveal(&state, word, cx);
2846 assert!(!is_pending(&state, cx));
2847 let now = scroll_top(&state, cx);
2848 assert_eq!(
2849 (now.item_ix, now.offset_in_item),
2850 (top.item_ix, top.offset_in_item),
2851 "{word}"
2852 );
2853 }
2854 }
2855
2856 #[gpui::test]
2857 fn an_enclosing_list_scrolls_to_a_line_of_a_fit_content_view(cx: &mut TestAppContext) {
2858 let outer = ListState::new(2, ListAlignment::Top, px(1000.));
2859 let (state, cx) = window(&words(400), Container::List(outer.clone()), cx);
2860 reveal(&state, "w390", cx);
2861 assert!(!is_pending(&state, cx));
2862 let top = outer.logical_scroll_top();
2863 assert_eq!(top.item_ix, 1, "{top:?}");
2864 assert!(top.offset_in_item > px(100.), "{top:?}");
2865 }
2866
2867 #[gpui::test]
2868 fn on_reveal_scrolls_a_container_that_ignores_scroll_requests(cx: &mut TestAppContext) {
2869 let handle = ScrollHandle::new();
2870 let (state, cx) = window(&words(400), Container::Div(handle.clone()), cx);
2871 reveal(&state, "w390", cx);
2872 assert!(!is_pending(&state, cx));
2873 assert!(handle.offset().y < px(-100.), "{:?}", handle.offset());
2874 }
2875
2876 #[gpui::test]
2877 fn a_reveal_that_cannot_be_shown_gives_up(cx: &mut TestAppContext) {
2878 let (state, cx) = window(&words(4000), Container::Fixed, cx);
2879 reveal(&state, "w3990", cx);
2880 assert!(is_pending(&state, cx));
2881 for _ in 0..10 {
2882 draw(cx);
2883 }
2884 assert!(!is_pending(&state, cx));
2885 }
2886
2887 #[gpui::test]
2888 fn a_reveal_not_carried_out_in_time_is_dropped(cx: &mut TestAppContext) {
2889 let (state, cx) = window(¶graphs(200), Container::Scrollable, cx);
2890 request(&state, "paragraph 150", cx, |_, cx| {
2891 cx.background_executor()
2892 .advance_clock(std::time::Duration::from_secs(2))
2893 });
2894 draw(cx);
2895 assert!(!is_pending(&state, cx));
2896 assert_eq!(scroll_top(&state, cx).item_ix, 0);
2897 }
2898
2899 #[gpui::test]
2900 fn an_empty_range_reveals_its_line(cx: &mut TestAppContext) {
2901 let (state, cx) = window(&words(400), Container::Scrollable, cx);
2902 reveal(&state, "w390", cx);
2903 let top = scroll_top(&state, cx);
2904 state.update(cx, |state, cx| {
2906 let text = state.rendered_text();
2907 let start = text.as_str().find("w391").unwrap();
2908 state.reveal_range(start..start, cx).unwrap();
2909 });
2910 for _ in 0..3 {
2911 draw(cx);
2912 }
2913 assert!(!is_pending(&state, cx));
2914 let now = scroll_top(&state, cx);
2915 assert_eq!(
2916 (now.item_ix, now.offset_in_item),
2917 (top.item_ix, top.offset_in_item)
2918 );
2919 }
2920
2921 #[gpui::test]
2922 fn a_position_after_the_last_character_reveals_its_line(cx: &mut TestAppContext) {
2923 let (state, cx) = window(&words(400), Container::Scrollable, cx);
2924 reveal(&state, "w399", cx);
2925 let top = scroll_top(&state, cx);
2926 assert!(top.offset_in_item > px(1000.), "{top:?}");
2927 state.update(cx, |state, cx| {
2929 let text = state.rendered_text();
2930 let end = text.as_str().find("w399").unwrap() + "w399".len();
2931 state.reveal_range(end..end, cx).unwrap();
2932 });
2933 for _ in 0..3 {
2934 draw(cx);
2935 }
2936 assert!(!is_pending(&state, cx));
2937 let now = scroll_top(&state, cx);
2938 assert_eq!(
2939 (now.item_ix, now.offset_in_item),
2940 (top.item_ix, top.offset_in_item)
2941 );
2942 }
2943
2944 fn reveal_at(
2946 state: &Entity<TextViewState>,
2947 range: impl FnOnce(&str) -> std::ops::Range<usize>,
2948 cx: &mut VisualTestContext,
2949 ) {
2950 state.update(cx, |state, cx| {
2951 let text = state.rendered_text();
2952 let range = range(text.as_str());
2953 state.reveal_range(range, cx).unwrap();
2954 });
2955 for _ in 0..3 {
2956 draw(cx);
2957 }
2958 }
2959
2960 fn assert_unmoved(
2961 state: &Entity<TextViewState>,
2962 top: gpui::ListOffset,
2963 cx: &mut VisualTestContext,
2964 ) {
2965 assert!(!is_pending(state, cx));
2966 let now = scroll_top(state, cx);
2967 assert_eq!(
2968 (now.item_ix, now.offset_in_item),
2969 (top.item_ix, top.offset_in_item)
2970 );
2971 }
2972
2973 #[gpui::test]
2974 fn the_end_of_the_text_and_its_separators_reveal_the_last_line(cx: &mut TestAppContext) {
2975 let (state, cx) = window(&words(400), Container::Scrollable, cx);
2976 reveal(&state, "w399", cx);
2977 let top = scroll_top(&state, cx);
2978 assert!(top.offset_in_item > px(1000.), "{top:?}");
2979 reveal_at(&state, |text| text.len()..text.len(), cx);
2981 assert_unmoved(&state, top, cx);
2982 reveal_at(&state, |text| text.len() - 1..text.len(), cx);
2984 assert_unmoved(&state, top, cx);
2985
2986 let code = (0..200)
2987 .map(|ix| format!("line {ix}"))
2988 .collect::<Vec<_>>()
2989 .join("\n");
2990 state.update(cx, |state, cx| {
2991 state.set_text(&format!("```\n{code}\n```"), cx)
2992 });
2993 cx.run_until_parked();
2994 reveal(&state, "line 199", cx);
2995 let top = scroll_top(&state, cx);
2996 assert!(top.offset_in_item > px(1000.), "{top:?}");
2997 reveal_at(&state, |text| text.len()..text.len(), cx);
2998 assert_unmoved(&state, top, cx);
2999 }
3000
3001 #[gpui::test]
3002 fn the_end_of_a_block_above_reveals_its_last_line(cx: &mut TestAppContext) {
3003 let second = (0..400)
3004 .map(|ix| format!("v{ix}"))
3005 .collect::<Vec<_>>()
3006 .join(" ");
3007 let markdown = format!("{}\n\n{second}", words(400));
3008 let (state, cx) = window(&markdown, Container::Scrollable, cx);
3009 reveal(&state, "v399", cx);
3010 assert_eq!(scroll_top(&state, cx).item_ix, 1);
3011 reveal_at(
3013 &state,
3014 |text| {
3015 let end = text.find("w399").unwrap() + "w399".len();
3016 end..end
3017 },
3018 cx,
3019 );
3020 assert!(!is_pending(&state, cx));
3021 let top = scroll_top(&state, cx);
3022 assert_eq!(top.item_ix, 0, "{top:?}");
3023 assert!(top.offset_in_item > px(1000.), "{top:?}");
3024 }
3025
3026 #[gpui::test]
3027 fn an_empty_view_has_nothing_to_reveal(cx: &mut TestAppContext) {
3028 cx.update(crate::init);
3029 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
3030 cx.run_until_parked();
3031 state.update(cx, |state, cx| {
3032 assert_eq!(state.reveal_range(0..0, cx), Ok(()));
3033 assert!(state.pending_reveal.is_none());
3034 });
3035 }
3036
3037 #[gpui::test]
3038 fn revealing_a_visible_block_does_not_scroll(cx: &mut TestAppContext) {
3039 let markdown = format!("{}\n\n<div>html</div>\n\n{}", words(400), words(400));
3040 let (state, cx) = window(&markdown, Container::Scrollable, cx);
3041 reveal(&state, "html", cx);
3042 state.update(cx, |state, _| state.list_state.scroll_by(px(30.)));
3044 draw(cx);
3045 let top = scroll_top(&state, cx);
3046 reveal(&state, "html", cx);
3047 assert_unmoved(&state, top, cx);
3048 }
3049
3050 #[gpui::test]
3051 fn a_line_of_an_inline_flow_counts_as_shown_once_scrolled_to(cx: &mut TestAppContext) {
3052 let markdown = (0..400)
3055 .map(|ix| {
3056 if ix % 10 == 0 {
3057 format!("`c{ix}`")
3058 } else {
3059 format!("w{ix}")
3060 }
3061 })
3062 .collect::<Vec<_>>()
3063 .join(" ");
3064 let (state, cx) = window(&markdown, Container::Scrollable, cx);
3065 reveal(&state, "c390", cx);
3066 assert!(!is_pending(&state, cx));
3067 assert!(scroll_top(&state, cx).offset_in_item > px(1000.));
3068 }
3069
3070 #[gpui::test]
3071 fn a_range_starting_on_a_line_break_reveals_the_next_line(cx: &mut TestAppContext) {
3072 let code = (0..200)
3073 .map(|ix| format!("line {ix}"))
3074 .collect::<Vec<_>>()
3075 .join("\n");
3076 let (state, cx) = window(&format!("```\n{code}\n```"), Container::Scrollable, cx);
3077 reveal(&state, "\nline 190", cx);
3078 assert!(!is_pending(&state, cx));
3079 let top = scroll_top(&state, cx);
3080 assert!(top.offset_in_item > px(1000.), "{top:?}");
3081 }
3082
3083 #[gpui::test]
3084 fn a_range_starting_on_a_line_break_in_an_inline_flow_reveals_the_next_line(
3085 cx: &mut TestAppContext,
3086 ) {
3087 let lines = (0..200)
3089 .map(|ix| format!("line {ix} `code`"))
3090 .collect::<Vec<_>>()
3091 .join("\\\n");
3092 let (state, cx) = window(&lines, Container::Scrollable, cx);
3093 reveal(&state, "\nline 190", cx);
3094 assert!(!is_pending(&state, cx));
3095 let top = scroll_top(&state, cx);
3096 assert!(top.offset_in_item > px(1000.), "{top:?}");
3097 }
3098
3099 #[gpui::test]
3100 fn a_reveal_is_dropped_when_its_text_before_it_changes(cx: &mut TestAppContext) {
3101 let (state, cx) = window(¶graphs(200), Container::Scrollable, cx);
3102 let target = "first words then the target";
3103 let markdown = format!("{target}\n\n{}", paragraphs(200));
3104 state.update(cx, |state, cx| state.set_text(&markdown, cx));
3105 cx.run_until_parked();
3106
3107 request(&state, "target", cx, |state, cx| {
3109 state.set_text(&markdown.replacen("target", "target and more", 1), cx);
3110 assert!(state.pending_reveal.is_some());
3111 });
3112 request(&state, "target", cx, |state, cx| {
3114 state.set_text(&markdown.replacen("words", "WORDS", 1), cx);
3115 assert!(state.pending_reveal.is_none());
3116 });
3117 }
3118
3119 #[gpui::test]
3120 fn a_clamped_view_does_not_reveal(cx: &mut TestAppContext) {
3121 let outer = ListState::new(2, ListAlignment::Top, px(1000.));
3122 let (state, cx) = window(&words(400), Container::Clamped(outer.clone()), cx);
3123 reveal(&state, "w390", cx);
3124 assert!(!is_pending(&state, cx));
3125 assert_eq!(outer.logical_scroll_top().item_ix, 0);
3126 }
3127
3128 #[gpui::test]
3129 fn text_outside_every_block_reveals_its_block(cx: &mut TestAppContext) {
3130 let markdown = format!("{}\n\n<div>html text</div>", paragraphs(100));
3131 let (state, cx) = window(&markdown, Container::Scrollable, cx);
3132 reveal(&state, "html text", cx);
3133 assert!(!is_pending(&state, cx));
3134 assert!(
3135 scroll_top(&state, cx).item_ix >= 90,
3136 "{:?}",
3137 scroll_top(&state, cx)
3138 );
3139 }
3140
3141 #[gpui::test]
3142 fn a_reveal_follows_its_text_past_an_edit_before_it(cx: &mut TestAppContext) {
3143 let (state, cx) = window(¶graphs(200), Container::Scrollable, cx);
3144 request(&state, "paragraph 150", cx, |state, cx| {
3146 state.set_text(&format!("inserted\n\n{}", paragraphs(200)), cx);
3147 assert!(state.pending_reveal.is_some());
3148 });
3149 for _ in 0..3 {
3150 draw(cx);
3151 }
3152 assert!(!is_pending(&state, cx));
3153 let top = scroll_top(&state, cx);
3154 assert!((141..=151).contains(&top.item_ix), "{top:?}");
3155
3156 request(&state, "paragraph 150", cx, |state, cx| {
3158 state.set_text(¶graphs(200).replace("paragraph 150", "changed"), cx);
3159 assert!(state.pending_reveal.is_none());
3160 });
3161 }
3162
3163 #[gpui::test]
3164 fn malformed_ranges_and_html_views_are_rejected(cx: &mut TestAppContext) {
3165 cx.update(crate::init);
3166 let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("first\n\nsecond", cx)));
3167 cx.run_until_parked();
3168 state.update(cx, |state, cx| {
3169 assert_eq!(
3170 state.reveal_range(std::ops::Range { start: 5, end: 3 }, cx),
3171 Err(RangeHighlightError::InvalidRange(0))
3172 );
3173 assert_eq!(
3174 state.reveal_range(0..100, cx),
3175 Err(RangeHighlightError::InvalidRange(0))
3176 );
3177 state.reveal_range(0..5, cx).unwrap();
3178 });
3179
3180 let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
3181 cx.run_until_parked();
3182 html.update(cx, |html, cx| {
3183 assert_eq!(
3184 html.reveal_range(0..3, cx),
3185 Err(RangeHighlightError::Unsupported)
3186 );
3187 });
3188 }
3189 }
3190}