text.rs

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