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