text.rs

  1use crate::{
  2    ActiveTooltip, AnyView, App, Bounds, DispatchPhase, Element, ElementId, GlobalElementId,
  3    HighlightStyle, Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId,
  4    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, Size, TextOverflow,
  5    TextRun, TextStyle, TooltipId, WhiteSpace, Window, WrappedLine, WrappedLineLayout,
  6    register_tooltip_mouse_handlers, set_tooltip_on_window,
  7};
  8use anyhow::Context as _;
  9use smallvec::SmallVec;
 10use std::{
 11    cell::{Cell, RefCell},
 12    mem,
 13    ops::Range,
 14    rc::Rc,
 15    sync::Arc,
 16};
 17use util::ResultExt;
 18
 19impl Element for &'static str {
 20    type RequestLayoutState = TextLayout;
 21    type PrepaintState = ();
 22
 23    fn id(&self) -> Option<ElementId> {
 24        None
 25    }
 26
 27    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 28        None
 29    }
 30
 31    fn request_layout(
 32        &mut self,
 33        _id: Option<&GlobalElementId>,
 34        _inspector_id: Option<&InspectorElementId>,
 35        window: &mut Window,
 36        cx: &mut App,
 37    ) -> (LayoutId, Self::RequestLayoutState) {
 38        let mut state = TextLayout::default();
 39        let layout_id = state.layout(SharedString::from(*self), None, window, cx);
 40        (layout_id, state)
 41    }
 42
 43    fn prepaint(
 44        &mut self,
 45        _id: Option<&GlobalElementId>,
 46        _inspector_id: Option<&InspectorElementId>,
 47        bounds: Bounds<Pixels>,
 48        text_layout: &mut Self::RequestLayoutState,
 49        _window: &mut Window,
 50        _cx: &mut App,
 51    ) {
 52        text_layout.prepaint(bounds, self)
 53    }
 54
 55    fn paint(
 56        &mut self,
 57        _id: Option<&GlobalElementId>,
 58        _inspector_id: Option<&InspectorElementId>,
 59        _bounds: Bounds<Pixels>,
 60        text_layout: &mut TextLayout,
 61        _: &mut (),
 62        window: &mut Window,
 63        cx: &mut App,
 64    ) {
 65        text_layout.paint(self, window, cx)
 66    }
 67}
 68
 69impl IntoElement for &'static str {
 70    type Element = Self;
 71
 72    fn into_element(self) -> Self::Element {
 73        self
 74    }
 75}
 76
 77impl IntoElement for String {
 78    type Element = SharedString;
 79
 80    fn into_element(self) -> Self::Element {
 81        self.into()
 82    }
 83}
 84
 85impl Element for SharedString {
 86    type RequestLayoutState = TextLayout;
 87    type PrepaintState = ();
 88
 89    fn id(&self) -> Option<ElementId> {
 90        None
 91    }
 92
 93    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 94        None
 95    }
 96
 97    fn request_layout(
 98        &mut self,
 99        _id: Option<&GlobalElementId>,
100        _inspector_id: Option<&InspectorElementId>,
101        window: &mut Window,
102        cx: &mut App,
103    ) -> (LayoutId, Self::RequestLayoutState) {
104        let mut state = TextLayout::default();
105        let layout_id = state.layout(self.clone(), None, window, cx);
106        (layout_id, state)
107    }
108
109    fn prepaint(
110        &mut self,
111        _id: Option<&GlobalElementId>,
112        _inspector_id: Option<&InspectorElementId>,
113        bounds: Bounds<Pixels>,
114        text_layout: &mut Self::RequestLayoutState,
115        _window: &mut Window,
116        _cx: &mut App,
117    ) {
118        text_layout.prepaint(bounds, self.as_ref())
119    }
120
121    fn paint(
122        &mut self,
123        _id: Option<&GlobalElementId>,
124        _inspector_id: Option<&InspectorElementId>,
125        _bounds: Bounds<Pixels>,
126        text_layout: &mut Self::RequestLayoutState,
127        _: &mut Self::PrepaintState,
128        window: &mut Window,
129        cx: &mut App,
130    ) {
131        text_layout.paint(self.as_ref(), window, cx)
132    }
133}
134
135impl IntoElement for SharedString {
136    type Element = Self;
137
138    fn into_element(self) -> Self::Element {
139        self
140    }
141}
142
143/// Renders text with runs of different styles.
144///
145/// Callers are responsible for setting the correct style for each run.
146/// For text with a uniform style, you can usually avoid calling this constructor
147/// and just pass text directly.
148pub struct StyledText {
149    text: SharedString,
150    runs: Option<Vec<TextRun>>,
151    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
152    layout: TextLayout,
153}
154
155impl StyledText {
156    /// Construct a new styled text element from the given string.
157    pub fn new(text: impl Into<SharedString>) -> Self {
158        StyledText {
159            text: text.into(),
160            runs: None,
161            delayed_highlights: None,
162            layout: TextLayout::default(),
163        }
164    }
165
166    /// Get the layout for this element. This can be used to map indices to pixels and vice versa.
167    pub fn layout(&self) -> &TextLayout {
168        &self.layout
169    }
170
171    /// Set the styling attributes for the given text, as well as
172    /// as any ranges of text that have had their style customized.
173    pub fn with_default_highlights(
174        mut self,
175        default_style: &TextStyle,
176        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
177    ) -> Self {
178        debug_assert!(
179            self.delayed_highlights.is_none(),
180            "Can't use `with_default_highlights` and `with_highlights`"
181        );
182        let runs = Self::compute_runs(&self.text, default_style, highlights);
183        self.runs = Some(runs);
184        self
185    }
186
187    /// Set the styling attributes for the given text, as well as
188    /// as any ranges of text that have had their style customized.
189    pub fn with_highlights(
190        mut self,
191        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
192    ) -> Self {
193        debug_assert!(
194            self.runs.is_none(),
195            "Can't use `with_highlights` and `with_default_highlights`"
196        );
197        self.delayed_highlights = Some(highlights.into_iter().collect::<Vec<_>>());
198        self
199    }
200
201    fn compute_runs(
202        text: &str,
203        default_style: &TextStyle,
204        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
205    ) -> Vec<TextRun> {
206        let mut runs = Vec::new();
207        let mut ix = 0;
208        for (range, highlight) in highlights {
209            if ix < range.start {
210                runs.push(default_style.clone().to_run(range.start - ix));
211            }
212            runs.push(
213                default_style
214                    .clone()
215                    .highlight(highlight)
216                    .to_run(range.len()),
217            );
218            ix = range.end;
219        }
220        if ix < text.len() {
221            runs.push(default_style.to_run(text.len() - ix));
222        }
223        runs
224    }
225
226    /// Set the text runs for this piece of text.
227    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
228        self.runs = Some(runs);
229        self
230    }
231}
232
233impl Element for StyledText {
234    type RequestLayoutState = ();
235    type PrepaintState = ();
236
237    fn id(&self) -> Option<ElementId> {
238        None
239    }
240
241    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
242        None
243    }
244
245    fn request_layout(
246        &mut self,
247        _id: Option<&GlobalElementId>,
248        _inspector_id: Option<&InspectorElementId>,
249        window: &mut Window,
250        cx: &mut App,
251    ) -> (LayoutId, Self::RequestLayoutState) {
252        let runs = self.runs.take().or_else(|| {
253            self.delayed_highlights.take().map(|delayed_highlights| {
254                Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
255            })
256        });
257
258        let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
259        (layout_id, ())
260    }
261
262    fn prepaint(
263        &mut self,
264        _id: Option<&GlobalElementId>,
265        _inspector_id: Option<&InspectorElementId>,
266        bounds: Bounds<Pixels>,
267        _: &mut Self::RequestLayoutState,
268        _window: &mut Window,
269        _cx: &mut App,
270    ) {
271        self.layout.prepaint(bounds, &self.text)
272    }
273
274    fn paint(
275        &mut self,
276        _id: Option<&GlobalElementId>,
277        _inspector_id: Option<&InspectorElementId>,
278        _bounds: Bounds<Pixels>,
279        _: &mut Self::RequestLayoutState,
280        _: &mut Self::PrepaintState,
281        window: &mut Window,
282        cx: &mut App,
283    ) {
284        self.layout.paint(&self.text, window, cx)
285    }
286}
287
288impl IntoElement for StyledText {
289    type Element = Self;
290
291    fn into_element(self) -> Self::Element {
292        self
293    }
294}
295
296/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
297#[derive(Default, Clone)]
298pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);
299
300struct TextLayoutInner {
301    len: usize,
302    lines: SmallVec<[WrappedLine; 1]>,
303    line_height: Pixels,
304    wrap_width: Option<Pixels>,
305    size: Option<Size<Pixels>>,
306    bounds: Option<Bounds<Pixels>>,
307}
308
309impl TextLayout {
310    fn layout(
311        &self,
312        text: SharedString,
313        runs: Option<Vec<TextRun>>,
314        window: &mut Window,
315        _: &mut App,
316    ) -> LayoutId {
317        let text_style = window.text_style();
318        let font_size = text_style.font_size.to_pixels(window.rem_size());
319        let line_height = text_style
320            .line_height
321            .to_pixels(font_size.into(), window.rem_size());
322
323        let mut runs = if let Some(runs) = runs {
324            runs
325        } else {
326            vec![text_style.to_run(text.len())]
327        };
328
329        window.request_measured_layout(Default::default(), {
330            let element_state = self.clone();
331
332            move |known_dimensions, available_space, window, cx| {
333                let wrap_width = if text_style.white_space == WhiteSpace::Normal {
334                    known_dimensions.width.or(match available_space.width {
335                        crate::AvailableSpace::Definite(x) => Some(x),
336                        _ => None,
337                    })
338                } else {
339                    None
340                };
341
342                let (truncate_width, truncation_suffix) =
343                    if let Some(text_overflow) = text_style.text_overflow.clone() {
344                        let width = known_dimensions.width.or(match available_space.width {
345                            crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
346                                Some(max_lines) => Some(x * max_lines),
347                                None => Some(x),
348                            },
349                            _ => None,
350                        });
351
352                        match text_overflow {
353                            TextOverflow::Truncate(s) => (width, s),
354                        }
355                    } else {
356                        (None, "".into())
357                    };
358
359                if let Some(text_layout) = element_state.0.borrow().as_ref()
360                    && text_layout.size.is_some()
361                    && (wrap_width.is_none() || wrap_width == text_layout.wrap_width)
362                {
363                    return text_layout.size.unwrap();
364                }
365
366                let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
367                let text = if let Some(truncate_width) = truncate_width {
368                    line_wrapper.truncate_line(
369                        text.clone(),
370                        truncate_width,
371                        &truncation_suffix,
372                        &mut runs,
373                    )
374                } else {
375                    text.clone()
376                };
377                let len = text.len();
378
379                let Some(lines) = window
380                    .text_system()
381                    .shape_text(
382                        text,
383                        font_size,
384                        &runs,
385                        wrap_width,            // Wrap if we know the width.
386                        text_style.line_clamp, // Limit the number of lines if line_clamp is set.
387                    )
388                    .log_err()
389                else {
390                    element_state.0.borrow_mut().replace(TextLayoutInner {
391                        lines: Default::default(),
392                        len: 0,
393                        line_height,
394                        wrap_width,
395                        size: Some(Size::default()),
396                        bounds: None,
397                    });
398                    return Size::default();
399                };
400
401                let mut size: Size<Pixels> = Size::default();
402                for line in &lines {
403                    let line_size = line.size(line_height);
404                    size.height += line_size.height;
405                    size.width = size.width.max(line_size.width).ceil();
406                }
407
408                element_state.0.borrow_mut().replace(TextLayoutInner {
409                    lines,
410                    len,
411                    line_height,
412                    wrap_width,
413                    size: Some(size),
414                    bounds: None,
415                });
416
417                size
418            }
419        })
420    }
421
422    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
423        let mut element_state = self.0.borrow_mut();
424        let element_state = element_state
425            .as_mut()
426            .with_context(|| format!("measurement has not been performed on {text}"))
427            .unwrap();
428        element_state.bounds = Some(bounds);
429    }
430
431    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
432        let element_state = self.0.borrow();
433        let element_state = element_state
434            .as_ref()
435            .with_context(|| format!("measurement has not been performed on {text}"))
436            .unwrap();
437        let bounds = element_state
438            .bounds
439            .with_context(|| format!("prepaint has not been performed on {text}"))
440            .unwrap();
441
442        let line_height = element_state.line_height;
443        let mut line_origin = bounds.origin;
444        let text_style = window.text_style();
445        for line in &element_state.lines {
446            line.paint_background(
447                line_origin,
448                line_height,
449                text_style.text_align,
450                Some(bounds),
451                window,
452                cx,
453            )
454            .log_err();
455            line.paint(
456                line_origin,
457                line_height,
458                text_style.text_align,
459                Some(bounds),
460                window,
461                cx,
462            )
463            .log_err();
464            line_origin.y += line.size(line_height).height;
465        }
466    }
467
468    /// Get the byte index into the input of the pixel position.
469    pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
470        let element_state = self.0.borrow();
471        let element_state = element_state
472            .as_ref()
473            .expect("measurement has not been performed");
474        let bounds = element_state
475            .bounds
476            .expect("prepaint has not been performed");
477
478        if position.y < bounds.top() {
479            return Err(0);
480        }
481
482        let line_height = element_state.line_height;
483        let mut line_origin = bounds.origin;
484        let mut line_start_ix = 0;
485        for line in &element_state.lines {
486            let line_bottom = line_origin.y + line.size(line_height).height;
487            if position.y > line_bottom {
488                line_origin.y = line_bottom;
489                line_start_ix += line.len() + 1;
490            } else {
491                let position_within_line = position - line_origin;
492                match line.index_for_position(position_within_line, line_height) {
493                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
494                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
495                }
496            }
497        }
498
499        Err(line_start_ix.saturating_sub(1))
500    }
501
502    /// Get the pixel position for the given byte index.
503    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
504        let element_state = self.0.borrow();
505        let element_state = element_state
506            .as_ref()
507            .expect("measurement has not been performed");
508        let bounds = element_state
509            .bounds
510            .expect("prepaint has not been performed");
511        let line_height = element_state.line_height;
512
513        let mut line_origin = bounds.origin;
514        let mut line_start_ix = 0;
515
516        for line in &element_state.lines {
517            let line_end_ix = line_start_ix + line.len();
518            if index < line_start_ix {
519                break;
520            } else if index > line_end_ix {
521                line_origin.y += line.size(line_height).height;
522                line_start_ix = line_end_ix + 1;
523                continue;
524            } else {
525                let ix_within_line = index - line_start_ix;
526                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
527            }
528        }
529
530        None
531    }
532
533    /// Retrieve the layout for the line containing the given byte index.
534    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
535        let element_state = self.0.borrow();
536        let element_state = element_state
537            .as_ref()
538            .expect("measurement has not been performed");
539        let bounds = element_state
540            .bounds
541            .expect("prepaint has not been performed");
542        let line_height = element_state.line_height;
543
544        let mut line_origin = bounds.origin;
545        let mut line_start_ix = 0;
546
547        for line in &element_state.lines {
548            let line_end_ix = line_start_ix + line.len();
549            if index < line_start_ix {
550                break;
551            } else if index > line_end_ix {
552                line_origin.y += line.size(line_height).height;
553                line_start_ix = line_end_ix + 1;
554                continue;
555            } else {
556                return Some(line.layout.clone());
557            }
558        }
559
560        None
561    }
562
563    /// The bounds of this layout.
564    pub fn bounds(&self) -> Bounds<Pixels> {
565        self.0.borrow().as_ref().unwrap().bounds.unwrap()
566    }
567
568    /// The line height for this layout.
569    pub fn line_height(&self) -> Pixels {
570        self.0.borrow().as_ref().unwrap().line_height
571    }
572
573    /// The UTF-8 length of the underlying text.
574    pub fn len(&self) -> usize {
575        self.0.borrow().as_ref().unwrap().len
576    }
577
578    /// The text for this layout.
579    pub fn text(&self) -> String {
580        self.0
581            .borrow()
582            .as_ref()
583            .unwrap()
584            .lines
585            .iter()
586            .map(|s| s.text.to_string())
587            .collect::<Vec<_>>()
588            .join("\n")
589    }
590
591    /// The text for this layout (with soft-wraps as newlines)
592    pub fn wrapped_text(&self) -> String {
593        let mut lines = Vec::new();
594        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
595            let mut seen = 0;
596            for boundary in wrapped.layout.wrap_boundaries.iter() {
597                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
598                    [boundary.glyph_ix]
599                    .index;
600
601                lines.push(wrapped.text[seen..index].to_string());
602                seen = index;
603            }
604            lines.push(wrapped.text[seen..].to_string());
605        }
606
607        lines.join("\n")
608    }
609}
610
611/// A text element that can be interacted with.
612pub struct InteractiveText {
613    element_id: ElementId,
614    text: StyledText,
615    click_listener:
616        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
617    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
618    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
619    tooltip_id: Option<TooltipId>,
620    clickable_ranges: Vec<Range<usize>>,
621}
622
623struct InteractiveTextClickEvent {
624    mouse_down_index: usize,
625    mouse_up_index: usize,
626}
627
628#[doc(hidden)]
629#[derive(Default)]
630pub struct InteractiveTextState {
631    mouse_down_index: Rc<Cell<Option<usize>>>,
632    hovered_index: Rc<Cell<Option<usize>>>,
633    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
634}
635
636/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
637impl InteractiveText {
638    /// Creates a new InteractiveText from the given text.
639    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
640        Self {
641            element_id: id.into(),
642            text,
643            click_listener: None,
644            hover_listener: None,
645            tooltip_builder: None,
646            tooltip_id: None,
647            clickable_ranges: Vec::new(),
648        }
649    }
650
651    /// on_click is called when the user clicks on one of the given ranges, passing the index of
652    /// the clicked range.
653    pub fn on_click(
654        mut self,
655        ranges: Vec<Range<usize>>,
656        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
657    ) -> Self {
658        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
659            for (range_ix, range) in ranges.iter().enumerate() {
660                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
661                {
662                    listener(range_ix, window, cx);
663                }
664            }
665        }));
666        self.clickable_ranges = ranges;
667        self
668    }
669
670    /// on_hover is called when the mouse moves over a character within the text, passing the
671    /// index of the hovered character, or None if the mouse leaves the text.
672    pub fn on_hover(
673        mut self,
674        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
675    ) -> Self {
676        self.hover_listener = Some(Box::new(listener));
677        self
678    }
679
680    /// tooltip lets you specify a tooltip for a given character index in the string.
681    pub fn tooltip(
682        mut self,
683        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
684    ) -> Self {
685        self.tooltip_builder = Some(Rc::new(builder));
686        self
687    }
688}
689
690impl Element for InteractiveText {
691    type RequestLayoutState = ();
692    type PrepaintState = Hitbox;
693
694    fn id(&self) -> Option<ElementId> {
695        Some(self.element_id.clone())
696    }
697
698    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
699        None
700    }
701
702    fn request_layout(
703        &mut self,
704        _id: Option<&GlobalElementId>,
705        inspector_id: Option<&InspectorElementId>,
706        window: &mut Window,
707        cx: &mut App,
708    ) -> (LayoutId, Self::RequestLayoutState) {
709        self.text.request_layout(None, inspector_id, window, cx)
710    }
711
712    fn prepaint(
713        &mut self,
714        global_id: Option<&GlobalElementId>,
715        inspector_id: Option<&InspectorElementId>,
716        bounds: Bounds<Pixels>,
717        state: &mut Self::RequestLayoutState,
718        window: &mut Window,
719        cx: &mut App,
720    ) -> Hitbox {
721        window.with_optional_element_state::<InteractiveTextState, _>(
722            global_id,
723            |interactive_state, window| {
724                let mut interactive_state = interactive_state
725                    .map(|interactive_state| interactive_state.unwrap_or_default());
726
727                if let Some(interactive_state) = interactive_state.as_mut() {
728                    if self.tooltip_builder.is_some() {
729                        self.tooltip_id =
730                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
731                    } else {
732                        // If there is no longer a tooltip builder, remove the active tooltip.
733                        interactive_state.active_tooltip.take();
734                    }
735                }
736
737                self.text
738                    .prepaint(None, inspector_id, bounds, state, window, cx);
739                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
740                (hitbox, interactive_state)
741            },
742        )
743    }
744
745    fn paint(
746        &mut self,
747        global_id: Option<&GlobalElementId>,
748        inspector_id: Option<&InspectorElementId>,
749        bounds: Bounds<Pixels>,
750        _: &mut Self::RequestLayoutState,
751        hitbox: &mut Hitbox,
752        window: &mut Window,
753        cx: &mut App,
754    ) {
755        let current_view = window.current_view();
756        let text_layout = self.text.layout().clone();
757        window.with_element_state::<InteractiveTextState, _>(
758            global_id.unwrap(),
759            |interactive_state, window| {
760                let mut interactive_state = interactive_state.unwrap_or_default();
761                if let Some(click_listener) = self.click_listener.take() {
762                    let mouse_position = window.mouse_position();
763                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
764                        && self
765                            .clickable_ranges
766                            .iter()
767                            .any(|range| range.contains(&ix))
768                    {
769                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
770                    }
771
772                    let text_layout = text_layout.clone();
773                    let mouse_down = interactive_state.mouse_down_index.clone();
774                    if let Some(mouse_down_index) = mouse_down.get() {
775                        let hitbox = hitbox.clone();
776                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
777                        window.on_mouse_event(
778                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
779                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
780                                    if let Ok(mouse_up_index) =
781                                        text_layout.index_for_position(event.position)
782                                    {
783                                        click_listener(
784                                            &clickable_ranges,
785                                            InteractiveTextClickEvent {
786                                                mouse_down_index,
787                                                mouse_up_index,
788                                            },
789                                            window,
790                                            cx,
791                                        )
792                                    }
793
794                                    mouse_down.take();
795                                    window.refresh();
796                                }
797                            },
798                        );
799                    } else {
800                        let hitbox = hitbox.clone();
801                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
802                            if phase == DispatchPhase::Bubble
803                                && hitbox.is_hovered(window)
804                                && let Ok(mouse_down_index) =
805                                    text_layout.index_for_position(event.position)
806                            {
807                                mouse_down.set(Some(mouse_down_index));
808                                window.refresh();
809                            }
810                        });
811                    }
812                }
813
814                window.on_mouse_event({
815                    let mut hover_listener = self.hover_listener.take();
816                    let hitbox = hitbox.clone();
817                    let text_layout = text_layout.clone();
818                    let hovered_index = interactive_state.hovered_index.clone();
819                    move |event: &MouseMoveEvent, phase, window, cx| {
820                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
821                            let current = hovered_index.get();
822                            let updated = text_layout.index_for_position(event.position).ok();
823                            if current != updated {
824                                hovered_index.set(updated);
825                                if let Some(hover_listener) = hover_listener.as_ref() {
826                                    hover_listener(updated, event.clone(), window, cx);
827                                }
828                                cx.notify(current_view);
829                            }
830                        }
831                    }
832                });
833
834                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
835                    let active_tooltip = interactive_state.active_tooltip.clone();
836                    let build_tooltip = Rc::new({
837                        let tooltip_is_hoverable = false;
838                        let text_layout = text_layout.clone();
839                        move |window: &mut Window, cx: &mut App| {
840                            text_layout
841                                .index_for_position(window.mouse_position())
842                                .ok()
843                                .and_then(|position| tooltip_builder(position, window, cx))
844                                .map(|view| (view, tooltip_is_hoverable))
845                        }
846                    });
847
848                    // Use bounds instead of testing hitbox since this is called during prepaint.
849                    let check_is_hovered_during_prepaint = Rc::new({
850                        let source_bounds = hitbox.bounds;
851                        let text_layout = text_layout.clone();
852                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
853                        move |window: &Window| {
854                            text_layout
855                                .index_for_position(window.mouse_position())
856                                .is_ok()
857                                && source_bounds.contains(&window.mouse_position())
858                                && pending_mouse_down.get().is_none()
859                        }
860                    });
861
862                    let check_is_hovered = Rc::new({
863                        let hitbox = hitbox.clone();
864                        let text_layout = text_layout.clone();
865                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
866                        move |window: &Window| {
867                            text_layout
868                                .index_for_position(window.mouse_position())
869                                .is_ok()
870                                && hitbox.is_hovered(window)
871                                && pending_mouse_down.get().is_none()
872                        }
873                    });
874
875                    register_tooltip_mouse_handlers(
876                        &active_tooltip,
877                        self.tooltip_id,
878                        build_tooltip,
879                        check_is_hovered,
880                        check_is_hovered_during_prepaint,
881                        window,
882                    );
883                }
884
885                self.text
886                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
887
888                ((), interactive_state)
889            },
890        );
891    }
892}
893
894impl IntoElement for InteractiveText {
895    type Element = Self;
896
897    fn into_element(self) -> Self::Element {
898        self
899    }
900}