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