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        let layout_id = 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        layout_id
422    }
423
424    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
425        let mut element_state = self.0.borrow_mut();
426        let element_state = element_state
427            .as_mut()
428            .with_context(|| format!("measurement has not been performed on {text}"))
429            .unwrap();
430        element_state.bounds = Some(bounds);
431    }
432
433    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
434        let element_state = self.0.borrow();
435        let element_state = element_state
436            .as_ref()
437            .with_context(|| format!("measurement has not been performed on {text}"))
438            .unwrap();
439        let bounds = element_state
440            .bounds
441            .with_context(|| format!("prepaint has not been performed on {text}"))
442            .unwrap();
443
444        let line_height = element_state.line_height;
445        let mut line_origin = bounds.origin;
446        let text_style = window.text_style();
447        for line in &element_state.lines {
448            line.paint_background(
449                line_origin,
450                line_height,
451                text_style.text_align,
452                Some(bounds),
453                window,
454                cx,
455            )
456            .log_err();
457            line.paint(
458                line_origin,
459                line_height,
460                text_style.text_align,
461                Some(bounds),
462                window,
463                cx,
464            )
465            .log_err();
466            line_origin.y += line.size(line_height).height;
467        }
468    }
469
470    /// Get the byte index into the input of the pixel position.
471    pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
472        let element_state = self.0.borrow();
473        let element_state = element_state
474            .as_ref()
475            .expect("measurement has not been performed");
476        let bounds = element_state
477            .bounds
478            .expect("prepaint has not been performed");
479
480        if position.y < bounds.top() {
481            return Err(0);
482        }
483
484        let line_height = element_state.line_height;
485        let mut line_origin = bounds.origin;
486        let mut line_start_ix = 0;
487        for line in &element_state.lines {
488            let line_bottom = line_origin.y + line.size(line_height).height;
489            if position.y > line_bottom {
490                line_origin.y = line_bottom;
491                line_start_ix += line.len() + 1;
492            } else {
493                let position_within_line = position - line_origin;
494                match line.index_for_position(position_within_line, line_height) {
495                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
496                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
497                }
498            }
499        }
500
501        Err(line_start_ix.saturating_sub(1))
502    }
503
504    /// Get the pixel position for the given byte index.
505    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
506        let element_state = self.0.borrow();
507        let element_state = element_state
508            .as_ref()
509            .expect("measurement has not been performed");
510        let bounds = element_state
511            .bounds
512            .expect("prepaint has not been performed");
513        let line_height = element_state.line_height;
514
515        let mut line_origin = bounds.origin;
516        let mut line_start_ix = 0;
517
518        for line in &element_state.lines {
519            let line_end_ix = line_start_ix + line.len();
520            if index < line_start_ix {
521                break;
522            } else if index > line_end_ix {
523                line_origin.y += line.size(line_height).height;
524                line_start_ix = line_end_ix + 1;
525                continue;
526            } else {
527                let ix_within_line = index - line_start_ix;
528                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
529            }
530        }
531
532        None
533    }
534
535    /// Retrieve the layout for the line containing the given byte index.
536    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
537        let element_state = self.0.borrow();
538        let element_state = element_state
539            .as_ref()
540            .expect("measurement has not been performed");
541        let bounds = element_state
542            .bounds
543            .expect("prepaint has not been performed");
544        let line_height = element_state.line_height;
545
546        let mut line_origin = bounds.origin;
547        let mut line_start_ix = 0;
548
549        for line in &element_state.lines {
550            let line_end_ix = line_start_ix + line.len();
551            if index < line_start_ix {
552                break;
553            } else if index > line_end_ix {
554                line_origin.y += line.size(line_height).height;
555                line_start_ix = line_end_ix + 1;
556                continue;
557            } else {
558                return Some(line.layout.clone());
559            }
560        }
561
562        None
563    }
564
565    /// The bounds of this layout.
566    pub fn bounds(&self) -> Bounds<Pixels> {
567        self.0.borrow().as_ref().unwrap().bounds.unwrap()
568    }
569
570    /// The line height for this layout.
571    pub fn line_height(&self) -> Pixels {
572        self.0.borrow().as_ref().unwrap().line_height
573    }
574
575    /// The UTF-8 length of the underlying text.
576    pub fn len(&self) -> usize {
577        self.0.borrow().as_ref().unwrap().len
578    }
579
580    /// The text for this layout.
581    pub fn text(&self) -> String {
582        self.0
583            .borrow()
584            .as_ref()
585            .unwrap()
586            .lines
587            .iter()
588            .map(|s| s.text.to_string())
589            .collect::<Vec<_>>()
590            .join("\n")
591    }
592
593    /// The text for this layout (with soft-wraps as newlines)
594    pub fn wrapped_text(&self) -> String {
595        let mut lines = Vec::new();
596        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
597            let mut seen = 0;
598            for boundary in wrapped.layout.wrap_boundaries.iter() {
599                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
600                    [boundary.glyph_ix]
601                    .index;
602
603                lines.push(wrapped.text[seen..index].to_string());
604                seen = index;
605            }
606            lines.push(wrapped.text[seen..].to_string());
607        }
608
609        lines.join("\n")
610    }
611}
612
613/// A text element that can be interacted with.
614pub struct InteractiveText {
615    element_id: ElementId,
616    text: StyledText,
617    click_listener:
618        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
619    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
620    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
621    tooltip_id: Option<TooltipId>,
622    clickable_ranges: Vec<Range<usize>>,
623}
624
625struct InteractiveTextClickEvent {
626    mouse_down_index: usize,
627    mouse_up_index: usize,
628}
629
630#[doc(hidden)]
631#[derive(Default)]
632pub struct InteractiveTextState {
633    mouse_down_index: Rc<Cell<Option<usize>>>,
634    hovered_index: Rc<Cell<Option<usize>>>,
635    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
636}
637
638/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
639impl InteractiveText {
640    /// Creates a new InteractiveText from the given text.
641    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
642        Self {
643            element_id: id.into(),
644            text,
645            click_listener: None,
646            hover_listener: None,
647            tooltip_builder: None,
648            tooltip_id: None,
649            clickable_ranges: Vec::new(),
650        }
651    }
652
653    /// on_click is called when the user clicks on one of the given ranges, passing the index of
654    /// the clicked range.
655    pub fn on_click(
656        mut self,
657        ranges: Vec<Range<usize>>,
658        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
659    ) -> Self {
660        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
661            for (range_ix, range) in ranges.iter().enumerate() {
662                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
663                {
664                    listener(range_ix, window, cx);
665                }
666            }
667        }));
668        self.clickable_ranges = ranges;
669        self
670    }
671
672    /// on_hover is called when the mouse moves over a character within the text, passing the
673    /// index of the hovered character, or None if the mouse leaves the text.
674    pub fn on_hover(
675        mut self,
676        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
677    ) -> Self {
678        self.hover_listener = Some(Box::new(listener));
679        self
680    }
681
682    /// tooltip lets you specify a tooltip for a given character index in the string.
683    pub fn tooltip(
684        mut self,
685        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
686    ) -> Self {
687        self.tooltip_builder = Some(Rc::new(builder));
688        self
689    }
690}
691
692impl Element for InteractiveText {
693    type RequestLayoutState = ();
694    type PrepaintState = Hitbox;
695
696    fn id(&self) -> Option<ElementId> {
697        Some(self.element_id.clone())
698    }
699
700    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
701        None
702    }
703
704    fn request_layout(
705        &mut self,
706        _id: Option<&GlobalElementId>,
707        inspector_id: Option<&InspectorElementId>,
708        window: &mut Window,
709        cx: &mut App,
710    ) -> (LayoutId, Self::RequestLayoutState) {
711        self.text.request_layout(None, inspector_id, window, cx)
712    }
713
714    fn prepaint(
715        &mut self,
716        global_id: Option<&GlobalElementId>,
717        inspector_id: Option<&InspectorElementId>,
718        bounds: Bounds<Pixels>,
719        state: &mut Self::RequestLayoutState,
720        window: &mut Window,
721        cx: &mut App,
722    ) -> Hitbox {
723        window.with_optional_element_state::<InteractiveTextState, _>(
724            global_id,
725            |interactive_state, window| {
726                let mut interactive_state = interactive_state
727                    .map(|interactive_state| interactive_state.unwrap_or_default());
728
729                if let Some(interactive_state) = interactive_state.as_mut() {
730                    if self.tooltip_builder.is_some() {
731                        self.tooltip_id =
732                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
733                    } else {
734                        // If there is no longer a tooltip builder, remove the active tooltip.
735                        interactive_state.active_tooltip.take();
736                    }
737                }
738
739                self.text
740                    .prepaint(None, inspector_id, bounds, state, window, cx);
741                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
742                (hitbox, interactive_state)
743            },
744        )
745    }
746
747    fn paint(
748        &mut self,
749        global_id: Option<&GlobalElementId>,
750        inspector_id: Option<&InspectorElementId>,
751        bounds: Bounds<Pixels>,
752        _: &mut Self::RequestLayoutState,
753        hitbox: &mut Hitbox,
754        window: &mut Window,
755        cx: &mut App,
756    ) {
757        let current_view = window.current_view();
758        let text_layout = self.text.layout().clone();
759        window.with_element_state::<InteractiveTextState, _>(
760            global_id.unwrap(),
761            |interactive_state, window| {
762                let mut interactive_state = interactive_state.unwrap_or_default();
763                if let Some(click_listener) = self.click_listener.take() {
764                    let mouse_position = window.mouse_position();
765                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
766                        && self
767                            .clickable_ranges
768                            .iter()
769                            .any(|range| range.contains(&ix))
770                    {
771                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
772                    }
773
774                    let text_layout = text_layout.clone();
775                    let mouse_down = interactive_state.mouse_down_index.clone();
776                    if let Some(mouse_down_index) = mouse_down.get() {
777                        let hitbox = hitbox.clone();
778                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
779                        window.on_mouse_event(
780                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
781                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
782                                    if let Ok(mouse_up_index) =
783                                        text_layout.index_for_position(event.position)
784                                    {
785                                        click_listener(
786                                            &clickable_ranges,
787                                            InteractiveTextClickEvent {
788                                                mouse_down_index,
789                                                mouse_up_index,
790                                            },
791                                            window,
792                                            cx,
793                                        )
794                                    }
795
796                                    mouse_down.take();
797                                    window.refresh();
798                                }
799                            },
800                        );
801                    } else {
802                        let hitbox = hitbox.clone();
803                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
804                            if phase == DispatchPhase::Bubble
805                                && hitbox.is_hovered(window)
806                                && let Ok(mouse_down_index) =
807                                    text_layout.index_for_position(event.position)
808                            {
809                                mouse_down.set(Some(mouse_down_index));
810                                window.refresh();
811                            }
812                        });
813                    }
814                }
815
816                window.on_mouse_event({
817                    let mut hover_listener = self.hover_listener.take();
818                    let hitbox = hitbox.clone();
819                    let text_layout = text_layout.clone();
820                    let hovered_index = interactive_state.hovered_index.clone();
821                    move |event: &MouseMoveEvent, phase, window, cx| {
822                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
823                            let current = hovered_index.get();
824                            let updated = text_layout.index_for_position(event.position).ok();
825                            if current != updated {
826                                hovered_index.set(updated);
827                                if let Some(hover_listener) = hover_listener.as_ref() {
828                                    hover_listener(updated, event.clone(), window, cx);
829                                }
830                                cx.notify(current_view);
831                            }
832                        }
833                    }
834                });
835
836                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
837                    let active_tooltip = interactive_state.active_tooltip.clone();
838                    let build_tooltip = Rc::new({
839                        let tooltip_is_hoverable = false;
840                        let text_layout = text_layout.clone();
841                        move |window: &mut Window, cx: &mut App| {
842                            text_layout
843                                .index_for_position(window.mouse_position())
844                                .ok()
845                                .and_then(|position| tooltip_builder(position, window, cx))
846                                .map(|view| (view, tooltip_is_hoverable))
847                        }
848                    });
849
850                    // Use bounds instead of testing hitbox since this is called during prepaint.
851                    let check_is_hovered_during_prepaint = Rc::new({
852                        let source_bounds = hitbox.bounds;
853                        let text_layout = text_layout.clone();
854                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
855                        move |window: &Window| {
856                            text_layout
857                                .index_for_position(window.mouse_position())
858                                .is_ok()
859                                && source_bounds.contains(&window.mouse_position())
860                                && pending_mouse_down.get().is_none()
861                        }
862                    });
863
864                    let check_is_hovered = Rc::new({
865                        let hitbox = hitbox.clone();
866                        let text_layout = text_layout.clone();
867                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
868                        move |window: &Window| {
869                            text_layout
870                                .index_for_position(window.mouse_position())
871                                .is_ok()
872                                && hitbox.is_hovered(window)
873                                && pending_mouse_down.get().is_none()
874                        }
875                    });
876
877                    register_tooltip_mouse_handlers(
878                        &active_tooltip,
879                        self.tooltip_id,
880                        build_tooltip,
881                        check_is_hovered,
882                        check_is_hovered_during_prepaint,
883                        window,
884                    );
885                }
886
887                self.text
888                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
889
890                ((), interactive_state)
891            },
892        );
893    }
894}
895
896impl IntoElement for InteractiveText {
897    type Element = Self;
898
899    fn into_element(self) -> Self::Element {
900        self
901    }
902}