1use std::cell::Cell;
4use std::time::{Duration, Instant};
5
6use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
7use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
8use ailloli_ui_core::{Constraints, EdgeInsets, FontId, Offset, Rect, Size, TextStyle};
9use ailloli_ui_runtime::app::{Invalidation, RuntimeHandle};
10use ailloli_ui_runtime::component::{
11 Binding, ComponentNode, Context, IntoView, Memo, Signal, View, Widget,
12};
13use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
14use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutResult};
15use ailloli_ui_runtime::popup::{position_popup, PopupContent, PopupDismissReason, PopupSemantics};
16use ailloli_ui_runtime::scene::PaintCtx;
17use ailloli_ui_text::{TextLayoutParams, WrapMode};
18
19use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
20use crate::layout::Container;
21use crate::text::Text;
22use crate::transactional_layout::TransactionalLayoutPending;
23
24use super::popup::{
25 resolve_popup_rect, window_viewport, PopupAlignment, PopupPlacement, PopupPortalBridge,
26};
27
28pub use crate::overlay::tooltip::TooltipStyle;
29
30const DEFAULT_OPEN_DELAY: Duration = Duration::from_millis(500);
32const DEFAULT_CLOSE_DELAY: Duration = Duration::from_millis(100);
34const DEFAULT_GAP: f32 = 6.0;
36
37#[derive(Clone)]
44enum TooltipContent {
45 Empty,
47 Label(Binding<String>),
49}
50
51impl TooltipContent {
52 fn text(&self) -> Option<String> {
54 match self {
55 Self::Empty => None,
56 Self::Label(label) => Some(label.read()),
57 }
58 }
59
60 fn has_text(&self) -> bool {
62 self.text().is_some_and(|text| !text.is_empty())
63 }
64
65 fn retained<A: 'static>(&self, style: TooltipStyle) -> PopupContent<A> {
67 match self {
68 Self::Empty => PopupContent::new(View::empty),
69 Self::Label(label) => {
70 let label = label.clone();
71 PopupContent::new(move || {
72 let text_style = TextStyle::new(FontId::Ui, style.font_px, style.fg);
73 let mut bubble = Container::<A>::new()
74 .fill()
75 .background(style.bg)
76 .radius(style.radius)
77 .child(
78 Text::new(label.clone())
79 .style(text_style)
80 .max_width(style.max_width.max(0.0))
81 .wrap_words(),
82 );
83 bubble.layout_mut().padding =
84 EdgeInsets::new(style.pad_x, style.pad_y, style.pad_x, style.pad_y);
85 bubble.into_view()
86 })
87 }
88 }
89 }
90}
91
92pub struct Tooltip<A = ()> {
115 pub(crate) layout: LayoutStyle,
117 pub(crate) flex_item: FlexItemStyle,
119 content: TooltipContent,
121 child: Option<View<A>>,
123 placement: PopupPlacement,
125 alignment: PopupAlignment,
127 disabled: Binding<bool>,
129 open_delay: Duration,
131 close_delay: Duration,
133 gap: f32,
135 style: TooltipStyle,
137}
138
139crate::impl_layout_builders!(Tooltip);
140
141impl<A: 'static> Default for Tooltip<A> {
142 fn default() -> Self {
143 Self::new()
144 }
145}
146
147impl<A: 'static> Tooltip<A> {
148 pub fn new() -> Self {
162 Self {
163 layout: LayoutStyle::default(),
164 flex_item: FlexItemStyle::default(),
165 content: TooltipContent::Empty,
166 child: None,
167 placement: PopupPlacement::Top,
168 alignment: PopupAlignment::Center,
169 disabled: Binding::Static(false),
170 open_delay: DEFAULT_OPEN_DELAY,
171 close_delay: DEFAULT_CLOSE_DELAY,
172 gap: DEFAULT_GAP,
173 style: TooltipStyle::default(),
174 }
175 }
176
177 pub fn with_label(content: impl Into<Binding<String>>) -> Self {
190 Self::new().content(content)
191 }
192
193 pub fn content(mut self, content: impl Into<Binding<String>>) -> Self {
212 self.content = TooltipContent::Label(content.into());
213 self
214 }
215
216 pub fn child(mut self, child: impl IntoView<A>) -> Self {
230 self.child = Some(child.into_view());
231 self
232 }
233
234 pub fn placement(mut self, placement: PopupPlacement) -> Self {
247 self.placement = placement;
248 self
249 }
250
251 pub fn alignment(mut self, alignment: PopupAlignment) -> Self {
261 self.alignment = alignment;
262 self
263 }
264
265 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
278 self.disabled = disabled.into();
279 self
280 }
281
282 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
293 self.disabled(disabled)
294 }
295
296 pub fn open_delay(mut self, delay: Duration) -> Self {
310 self.open_delay = delay;
311 self
312 }
313
314 pub fn close_delay(mut self, delay: Duration) -> Self {
329 self.close_delay = delay;
330 self
331 }
332
333 pub fn gap(mut self, gap: f32) -> Self {
345 self.gap = gap.max(0.0);
346 self
347 }
348
349 pub fn tooltip_style(mut self, style: TooltipStyle) -> Self {
363 self.style = style;
364 self
365 }
366}
367
368struct TooltipComponent<A> {
370 layout: LayoutStyle,
372 content: TooltipContent,
374 child: Option<View<A>>,
376 placement: PopupPlacement,
378 alignment: PopupAlignment,
380 disabled: Binding<bool>,
382 open_delay: Duration,
384 close_delay: Duration,
386 gap: f32,
388 style: TooltipStyle,
390}
391
392impl<A: 'static> ComponentNode<A> for TooltipComponent<A> {
393 fn build(&self, context: &mut Context<A>) -> View<A> {
394 let state = context.signal_with_invalidation(TooltipState::default(), Invalidation::Paint);
395 let children = self.child.clone().into_iter().collect();
396 let popup_content = self.content.retained(self.style);
397 View::node(
398 TooltipWidget {
399 layout: self.layout,
400 content: self.content.clone(),
401 placement: self.placement,
402 alignment: self.alignment,
403 disabled: self.disabled.clone(),
404 open_delay: self.open_delay,
405 close_delay: self.close_delay,
406 gap: self.gap,
407 style: self.style,
408 state,
409 owner: context.element_id(),
410 runtime: context.runtime(),
411 has_trigger: Cell::new(false),
412 pending_layout: Cell::new(None),
413 portal_presented: context.signal_with_invalidation(false, Invalidation::Paint),
414 popup: PopupPortalBridge::new_retained_with_content(
415 context,
416 PopupSemantics::tooltip(),
417 false,
418 popup_content,
419 ),
420 },
421 children,
422 )
423 }
424}
425
426impl<A: 'static> IntoView<A> for Tooltip<A> {
427 fn into_view(self) -> View<A> {
428 finish_view_sized(
429 View::component(TooltipComponent {
430 layout: self.layout,
431 content: self.content,
432 child: self.child,
433 placement: self.placement,
434 alignment: self.alignment,
435 disabled: self.disabled,
436 open_delay: self.open_delay,
437 close_delay: self.close_delay,
438 gap: self.gap,
439 style: self.style,
440 }),
441 self.flex_item,
442 LayoutSizeHint::from_layout(self.layout),
443 )
444 }
445}
446
447#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
448enum TooltipPhase {
450 #[default]
452 Hidden,
453 Opening(Instant),
455 Open,
457 Closing(Instant),
459}
460
461impl TooltipPhase {
462 fn is_painted(self) -> bool {
464 matches!(self, Self::Open | Self::Closing(_))
465 }
466}
467
468#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
469struct TooltipState {
471 phase: TooltipPhase,
473 hovered: bool,
475 focused: bool,
477 dismissed_until_hover_exit: bool,
479 dismissed_until_focus_exit: bool,
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484struct TooltipLayoutCommit {
486 has_trigger: bool,
488 close_portal: bool,
490}
491
492struct TooltipWidget<A> {
494 layout: LayoutStyle,
496 content: TooltipContent,
498 placement: PopupPlacement,
500 alignment: PopupAlignment,
502 disabled: Binding<bool>,
504 open_delay: Duration,
506 close_delay: Duration,
508 gap: f32,
510 style: TooltipStyle,
512 state: Signal<TooltipState>,
514 owner: ailloli_ui_core::ElementId,
516 runtime: RuntimeHandle<A>,
518 has_trigger: Cell<bool>,
520 pending_layout: Cell<Option<TransactionalLayoutPending<TooltipLayoutCommit>>>,
522 portal_presented: Signal<bool>,
524 popup: PopupPortalBridge<A>,
526}
527
528impl<A: 'static> Widget<A> for TooltipWidget<A> {
529 fn debug_name(&self) -> &'static str {
530 "Tooltip"
531 }
532
533 fn layout(
534 &self,
535 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
536 ctx: &mut LayoutCtx<'_>,
537 children: &mut [LayoutChild],
538 constraints: Constraints,
539 ) -> LayoutResult {
540 let mut child_layouts = Vec::new();
541 let mut intrinsic = Size::default();
542 if let Some(child) = children.first_mut() {
543 let result = child.layout(engine, ctx, constraints.loosen());
544 intrinsic = result.size;
545 child_layouts.push(ChildLayout {
546 offset: Offset::default(),
547 size: result.size,
548 paint_bounds: Rect::new(0.0, 0.0, result.size.w, result.size.h),
549 visual_bounds: result.visual_bounds,
550 });
551 }
552 let size = apply_layout_size(intrinsic, self.layout, constraints);
553 let has_trigger = !children.is_empty() && size.w > 0.0 && size.h > 0.0;
554 let available = !self.disabled.read() && has_trigger && self.content.has_text();
555 if ctx.layout_pass().is_committed() {
556 self.pending_layout.set(TransactionalLayoutPending::new(
557 ctx,
558 TooltipLayoutCommit {
559 has_trigger,
560 close_portal: !available,
561 },
562 ));
563 }
564 let bounds = Rect::new(0.0, 0.0, size.w, size.h);
565 LayoutResult {
566 size,
567 children: child_layouts,
568 paint_bounds: bounds,
569 visual_bounds: bounds,
570 overlay_hit_bounds: Vec::new(),
571 clip: None,
572 is_window_root_clip: false,
573 artifact: None,
574 }
575 }
576
577 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
579 let Some(commit) = self
580 .pending_layout
581 .take()
582 .and_then(|pending| pending.into_committed(ctx))
583 else {
584 return;
585 };
586 self.has_trigger.set(commit.has_trigger);
587 if commit.close_portal {
588 self.popup.close(PopupDismissReason::Programmatic);
589 self.portal_presented.set_if_changed(false);
590 }
591 }
592
593 fn paint(&self, ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
594 self.sync_focus_within(ctx.has_focus_within());
595 self.sync_hover(ctx.interaction().hovered, Instant::now());
596 }
597
598 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
599 let now = Instant::now();
600 self.sync_focus_within(ctx.has_focus_within());
601 self.sync_hover(ctx.interaction().hovered, now);
602 if self.consume_portal_dismissal() {
603 return;
604 }
605 if !self.resolve_phase(now).is_painted() || !self.is_available() {
606 self.popup.close(PopupDismissReason::Programmatic);
607 self.portal_presented.set_if_changed(false);
608 return;
609 }
610 let Some(label) = self.content.text().filter(|label| !label.is_empty()) else {
611 self.popup.close(PopupDismissReason::Programmatic);
612 self.portal_presented.set_if_changed(false);
613 return;
614 };
615 self.publish_label_geometry(ctx, bounds, &label);
616 }
617
618 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, _bounds: Rect, _layout: &LayoutResult) {
619 self.popup.refresh_owner(ctx);
620 if !self.is_available() {
621 self.hide(false, PopupDismissReason::Programmatic);
622 return;
623 }
624 match event {
625 Event::Focus(focus) if focus.focused => {
626 self.sync_focus_within(true);
627 self.popup.open_unpositioned(Some(ctx));
628 self.portal_presented.set_if_changed(true);
629 }
630 Event::Focus(_) => {
631 self.sync_focus_within(false);
632 self.popup.close(PopupDismissReason::OutsidePress);
633 self.portal_presented.set_if_changed(false);
634 }
635 Event::Keyboard(key)
636 if key.state == KeyState::Pressed
637 && matches!(&key.key, Key::Named(NamedKey::Escape))
638 && self.state.read().phase.is_painted() =>
639 {
640 self.hide(true, PopupDismissReason::Escape);
641 ctx.stop_propagation();
642 }
643 _ => {}
644 }
645 }
646
647 fn focus_policy(&self) -> FocusPolicy {
648 if !self.is_available() {
649 FocusPolicy::NotFocusable
650 } else {
651 FocusPolicy::Focusable
654 }
655 }
656}
657
658impl<A: 'static> TooltipWidget<A> {
659 fn is_available(&self) -> bool {
661 !self.disabled.read() && self.has_trigger.get() && self.content.has_text()
662 }
663
664 fn consume_portal_dismissal(&self) -> bool {
666 if !self.portal_presented.read() || self.popup.is_open() {
667 return false;
668 }
669 let mut state = self.state.read();
670 state.dismissed_until_focus_exit = state.focused;
671 state.dismissed_until_hover_exit = state.hovered;
672 state.phase = TooltipPhase::Hidden;
673 self.update_state(state);
674 self.portal_presented.set_if_changed(false);
675 true
676 }
677
678 fn sync_focus_within(&self, focused: bool) {
680 let focused = focused && self.is_available();
681 let mut state = self.state.read();
682 if state.focused == focused {
683 return;
684 }
685 state.focused = focused;
686 if focused {
687 if state.dismissed_until_focus_exit {
688 self.update_state(state);
689 return;
690 }
691 state.dismissed_until_hover_exit = false;
692 state.phase = TooltipPhase::Open;
693 } else {
694 state.dismissed_until_focus_exit = false;
695 state.dismissed_until_hover_exit = state.hovered;
696 state.phase = TooltipPhase::Hidden;
697 }
698 self.update_state(state);
699 }
700
701 fn sync_hover(&self, hovered: bool, now: Instant) {
703 let mut state = self.state.read();
704 let before = state;
705
706 if !self.is_available() {
707 state = TooltipState::default();
708 } else {
709 if state.hovered != hovered {
710 state.hovered = hovered;
711 if hovered {
712 if !state.focused && !state.dismissed_until_hover_exit {
713 state.phase = delayed_phase(now, self.open_delay, true);
714 }
715 } else {
716 state.dismissed_until_hover_exit = false;
717 if !state.focused {
718 state.phase = match state.phase {
719 TooltipPhase::Open | TooltipPhase::Closing(_) => {
720 delayed_phase(now, self.close_delay, false)
721 }
722 TooltipPhase::Opening(_) | TooltipPhase::Hidden => TooltipPhase::Hidden,
723 };
724 }
725 }
726 }
727
728 state.phase = resolve_deadline(state.phase, now);
729 }
730
731 if state != before {
732 self.update_state(state);
733 }
734 self.schedule_phase(state.phase, now);
735 }
736
737 fn resolve_phase(&self, now: Instant) -> TooltipPhase {
739 let mut state = self.state.read();
740 let phase = resolve_deadline(state.phase, now);
741 if phase != state.phase {
742 state.phase = phase;
743 self.update_state(state);
744 }
745 self.schedule_phase(phase, now);
746 phase
747 }
748
749 fn schedule_phase(&self, phase: TooltipPhase, now: Instant) {
751 let due = match phase {
752 TooltipPhase::Opening(due) | TooltipPhase::Closing(due) => due,
753 TooltipPhase::Hidden | TooltipPhase::Open => return,
754 };
755 self.runtime
756 .request_repaint_after(self.owner, due.saturating_duration_since(now));
757 }
758
759 fn update_state(&self, state: TooltipState) {
761 if self.state.read() != state {
762 self.state.set(state);
763 }
764 }
765
766 fn hide(&self, dismiss_until_hover_exit: bool, reason: PopupDismissReason) {
768 let mut state = self.state.read();
769 state.dismissed_until_focus_exit = dismiss_until_hover_exit && state.focused;
770 if !state.dismissed_until_focus_exit {
771 state.focused = false;
772 }
773 state.dismissed_until_hover_exit = dismiss_until_hover_exit && state.hovered;
774 state.phase = TooltipPhase::Hidden;
775 self.update_state(state);
776 self.popup.close(reason);
777 self.portal_presented.set_if_changed(false);
778 }
779
780 fn publish_label_geometry(&self, ctx: &mut PaintCtx<'_>, trigger: Rect, label: &str) {
785 let text_style = TextStyle::new(FontId::Ui, self.style.font_px, self.style.fg);
786 let Some(text_system) = ctx.text_system.as_deref_mut() else {
787 return;
788 };
789 let text = text_system.layout_cached(TextLayoutParams {
790 text: label,
791 style: text_style,
792 max_width: Some(self.style.max_width.max(0.0)),
793 wrap_mode: WrapMode::Word,
794 });
795 let width = text.metrics.width + self.style.pad_x * 2.0;
796 let height = text.metrics.height + self.style.pad_y * 2.0;
797 let desired_size = Size::new(width, height);
798 let card = if let Some(viewport) = window_viewport(ctx) {
799 resolve_popup_rect(
800 trigger,
801 desired_size,
802 viewport,
803 self.gap,
804 self.placement,
805 self.alignment,
806 true,
807 )
808 } else {
809 position_popup(
810 trigger,
811 desired_size,
812 self.placement,
813 self.alignment,
814 self.gap,
815 )
816 .unwrap_or(Rect::new(trigger.x, trigger.y, 0.0, 0.0))
817 };
818 self.popup.open_without_event(trigger, card);
819 self.portal_presented.set_if_changed(true);
820 }
821}
822
823fn delayed_phase(now: Instant, delay: Duration, opening: bool) -> TooltipPhase {
825 if delay.is_zero() {
826 if opening {
827 TooltipPhase::Open
828 } else {
829 TooltipPhase::Hidden
830 }
831 } else if opening {
832 TooltipPhase::Opening(now + delay)
833 } else {
834 TooltipPhase::Closing(now + delay)
835 }
836}
837
838fn resolve_deadline(phase: TooltipPhase, now: Instant) -> TooltipPhase {
840 match phase {
841 TooltipPhase::Opening(due) if due <= now => TooltipPhase::Open,
842 TooltipPhase::Closing(due) if due <= now => TooltipPhase::Hidden,
843 phase => phase,
844 }
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
853 use ailloli_ui_core::ClipShape;
854
855 #[test]
856 fn defaults_match_public_contract() {
857 let tooltip = Tooltip::<()>::new();
858 assert_eq!(tooltip.open_delay, Duration::from_millis(500));
859 assert_eq!(tooltip.close_delay, Duration::from_millis(100));
860 assert_eq!(tooltip.placement, PopupPlacement::Top);
861 assert_eq!(tooltip.alignment, PopupAlignment::Center);
862 }
863
864 #[test]
865 fn zero_delays_resolve_without_a_timer_tick() {
866 let now = Instant::now();
867 assert_eq!(delayed_phase(now, Duration::ZERO, true), TooltipPhase::Open);
868 assert_eq!(
869 delayed_phase(now, Duration::ZERO, false),
870 TooltipPhase::Hidden
871 );
872 }
873
874 #[test]
875 fn closing_grace_stays_painted_until_its_deadline() {
876 let now = Instant::now();
877 let phase = delayed_phase(now, Duration::from_millis(100), false);
878 assert!(phase.is_painted());
879 assert_eq!(resolve_deadline(phase, now), phase);
880 assert_eq!(
881 resolve_deadline(phase, now + Duration::from_millis(100)),
882 TooltipPhase::Hidden
883 );
884 }
885
886 #[test]
887 fn popup_clamps_to_window_root_instead_of_a_nested_scroll_clip() {
888 let root = Rect::new(0.0, 0.0, 640.0, 480.0);
889 let nested = Rect::new(20.0, 20.0, 100.0, 80.0);
890 let mut ctx = PaintCtx::new();
891 ctx.with_clip_shape(ClipShape::Rect(root), true, |ctx| {
892 ctx.with_clip_shape(ClipShape::Rect(nested), false, |ctx| {
893 assert_eq!(window_viewport(ctx), Some(root));
894 });
895 });
896 }
897}