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