ailloli_ui_widgets/controls/
tooltip.rs

1//! Retained text tooltips hosted through the shared popup portal.
2
3use 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
30/// Default hover/focus dwell time before opening a tooltip.
31const DEFAULT_OPEN_DELAY: Duration = Duration::from_millis(500);
32/// Default grace period before an open tooltip closes.
33const DEFAULT_CLOSE_DELAY: Duration = Duration::from_millis(100);
34/// Default logical-pixel separation between trigger and tooltip surface.
35const DEFAULT_GAP: f32 = 6.0;
36
37/// Text displayed by a [`Tooltip`].
38///
39/// This enum deliberately isolates content ownership from the trigger. The
40/// retained popup renderer currently supports text content. A future public
41/// arbitrary-view content API can extend this representation without changing
42/// the tooltip interaction state machine.
43#[derive(Clone)]
44enum TooltipContent {
45    /// No popup content; the tooltip remains unavailable.
46    Empty,
47    /// Static or reactive label; an empty current value remains unavailable.
48    Label(Binding<String>),
49}
50
51impl TooltipContent {
52    /// Reads and clones the current label, or returns `None` for empty content.
53    fn text(&self) -> Option<String> {
54        match self {
55            Self::Empty => None,
56            Self::Label(label) => Some(label.read()),
57        }
58    }
59
60    /// Returns whether the current content contains at least one byte.
61    fn has_text(&self) -> bool {
62        self.text().is_some_and(|text| !text.is_empty())
63    }
64
65    /// Builds the retained popup subtree from the current binding and style.
66    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
92/// A non-interactive text tooltip attached to one trigger view.
93///
94/// Text is mounted in the host's retained popup overlay through
95/// [`PopupContent`]. The trigger remains fully composable through
96/// [`Tooltip::child`]. Tooltip content is hit-tested by the popup host for
97/// correct z-order, but its non-interactive semantics never consume pointer
98/// input or enter focus traversal.
99///
100/// Hover opens after 500 ms and closes after a 100 ms grace period. Keyboard
101/// focus opens immediately; blur and `Escape` close immediately. Delays can be
102/// customized with [`Tooltip::open_delay`] and [`Tooltip::close_delay`].
103/// Empty content, missing/zero-sized triggers, and disabled state make the
104/// tooltip unavailable and close any mounted popup.
105///
106/// # Examples
107///
108/// ```
109/// use ailloli_ui_widgets::controls::{Button, Tooltip};
110/// let tooltip = Tooltip::with_label("Save changes")
111///     .child(Button::<()>::with_label("Save"));
112/// let _ = tooltip;
113/// ```
114pub struct Tooltip<A = ()> {
115    /// Layout configuration applied around the trigger.
116    pub(crate) layout: LayoutStyle,
117    /// Flex-item behavior used by the parent layout.
118    pub(crate) flex_item: FlexItemStyle,
119    /// Empty or reactive text content.
120    content: TooltipContent,
121    /// Optional sole trigger view; a later child replaces it.
122    child: Option<View<A>>,
123    /// Preferred side relative to the trigger.
124    placement: PopupPlacement,
125    /// Cross-axis alignment relative to the trigger.
126    alignment: PopupAlignment,
127    /// Live disabled state.
128    disabled: Binding<bool>,
129    /// Hover duration required before opening.
130    open_delay: Duration,
131    /// Hover-exit grace duration before closing an open tooltip.
132    close_delay: Duration,
133    /// Separation from the trigger in logical pixels.
134    gap: f32,
135    /// Bubble paint, padding, typography, and wrap bound.
136    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    /// Creates an empty tooltip. Add text with [`Self::content`] and a trigger
149    /// with [`Self::child`].
150    ///
151    /// Defaults are top/center placement, 500 ms hover-open delay, 100 ms
152    /// hover-close grace, and a 6-logical-pixel gap.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use ailloli_ui_widgets::controls::Tooltip;
158    /// let tooltip: Tooltip<()> = Tooltip::new();
159    /// let _ = tooltip;
160    /// ```
161    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    /// Creates a tooltip with retained text content.
178    ///
179    /// A trigger must still be supplied with [`Self::child`]. Empty current
180    /// content makes the tooltip unavailable.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use ailloli_ui_widgets::controls::Tooltip;
186    /// let tooltip: Tooltip<()> = Tooltip::with_label("Keyboard shortcut");
187    /// let _ = tooltip;
188    /// ```
189    pub fn with_label(content: impl Into<Binding<String>>) -> Self {
190        Self::new().content(content)
191    }
192
193    /// Sets the text rendered in the retained popup bubble.
194    ///
195    /// Static strings, `Signal<String>`, `State<String>`, and `Memo<String>` are
196    /// accepted through [`Binding`]. Arbitrary public view content remains
197    /// intentionally deferred while the shared portal already mounts this
198    /// specialized text subtree in the top-level overlay.
199    ///
200    /// A later call replaces the previous binding. `""` does not mount an empty
201    /// bubble; it disables and closes the tooltip until the binding is nonempty.
202    ///
203    /// # Examples
204    ///
205    /// ```
206    /// use ailloli_ui_runtime::component::Memo;
207    /// use ailloli_ui_widgets::controls::Tooltip;
208    /// let tooltip: Tooltip<()> = Tooltip::new().content(Memo::new(|| "Help".to_string()));
209    /// let _ = tooltip;
210    /// ```
211    pub fn content(mut self, content: impl Into<Binding<String>>) -> Self {
212        self.content = TooltipContent::Label(content.into());
213        self
214    }
215
216    /// Sets or replaces the trigger view.
217    ///
218    /// A trigger must resolve to nonzero width and height. Focusable children
219    /// keep normal focus routing; the tooltip shell is only a fallback focus
220    /// target for a non-focusable trigger.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use ailloli_ui_widgets::controls::{Button, Tooltip};
226    /// let tooltip = Tooltip::with_label("Create").child(Button::<()>::with_label("New"));
227    /// let _ = tooltip;
228    /// ```
229    pub fn child(mut self, child: impl IntoView<A>) -> Self {
230        self.child = Some(child.into_view());
231        self
232    }
233
234    /// Sets the preferred side of the popup relative to its trigger.
235    ///
236    /// When a window viewport is available, placement may flip and clamps to
237    /// remain visible; headless fallback uses the requested placement directly.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// use ailloli_ui_widgets::controls::{PopupPlacement, Tooltip};
243    /// let tooltip: Tooltip<()> = Tooltip::with_label("Details").placement(PopupPlacement::Bottom);
244    /// let _ = tooltip;
245    /// ```
246    pub fn placement(mut self, placement: PopupPlacement) -> Self {
247        self.placement = placement;
248        self
249    }
250
251    /// Sets popup alignment along the side selected by [`Self::placement`].
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// use ailloli_ui_widgets::controls::{PopupAlignment, Tooltip};
257    /// let tooltip: Tooltip<()> = Tooltip::with_label("Details").alignment(PopupAlignment::Start);
258    /// let _ = tooltip;
259    /// ```
260    pub fn alignment(mut self, alignment: PopupAlignment) -> Self {
261        self.alignment = alignment;
262        self
263    }
264
265    /// Sets a static or reactive disabled binding.
266    ///
267    /// Disabled state closes the popup, cancels pending phases, and removes the
268    /// tooltip shell from focus traversal; it does not disable the child itself.
269    ///
270    /// # Examples
271    ///
272    /// ```
273    /// use ailloli_ui_widgets::controls::Tooltip;
274    /// let tooltip: Tooltip<()> = Tooltip::with_label("Unavailable").disabled(true);
275    /// let _ = tooltip;
276    /// ```
277    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
278        self.disabled = disabled.into();
279        self
280    }
281
282    /// Convenience alias for [`Self::disabled`] with a reactive memo.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// use ailloli_ui_runtime::component::Memo;
288    /// use ailloli_ui_widgets::controls::Tooltip;
289    /// let tooltip: Tooltip<()> = Tooltip::with_label("Help").disabled_signal(Memo::new(|| false));
290    /// let _ = tooltip;
291    /// ```
292    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
293        self.disabled(disabled)
294    }
295
296    /// Sets the hover-open delay.
297    ///
298    /// [`Duration::ZERO`] opens on the same phase resolution without scheduling
299    /// a timer. Keyboard focus still opens immediately regardless of this value.
300    ///
301    /// # Examples
302    ///
303    /// ```
304    /// use std::time::Duration;
305    /// use ailloli_ui_widgets::controls::Tooltip;
306    /// let tooltip: Tooltip<()> = Tooltip::with_label("Instant").open_delay(Duration::ZERO);
307    /// let _ = tooltip;
308    /// ```
309    pub fn open_delay(mut self, delay: Duration) -> Self {
310        self.open_delay = delay;
311        self
312    }
313
314    /// Sets the grace period after hover leaves an already painted tooltip.
315    ///
316    /// This delay does not apply to blur, Escape, disabling, empty content, or
317    /// leaving during the opening phase. Zero closes on the same phase update.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// use std::time::Duration;
323    /// use ailloli_ui_widgets::controls::Tooltip;
324    /// let tooltip: Tooltip<()> =
325    ///     Tooltip::with_label("Help").close_delay(Duration::from_millis(250));
326    /// let _ = tooltip;
327    /// ```
328    pub fn close_delay(mut self, delay: Duration) -> Self {
329        self.close_delay = delay;
330        self
331    }
332
333    /// Sets trigger-to-popup separation in logical pixels, clamped to zero.
334    ///
335    /// `NaN` is treated as zero.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use ailloli_ui_widgets::controls::Tooltip;
341    /// let tooltip: Tooltip<()> = Tooltip::with_label("Help").gap(8.0);
342    /// let _ = tooltip;
343    /// ```
344    pub fn gap(mut self, gap: f32) -> Self {
345        self.gap = gap.max(0.0);
346        self
347    }
348
349    /// Replaces bubble colors, typography, padding, radius, and wrap width.
350    ///
351    /// The maximum text width is clamped to zero when measured; padding and
352    /// radius are otherwise accepted as-is.
353    ///
354    /// # Examples
355    ///
356    /// ```
357    /// use ailloli_ui_widgets::controls::{Tooltip, TooltipStyle};
358    /// let tooltip: Tooltip<()> =
359    ///     Tooltip::with_label("Help").tooltip_style(TooltipStyle::default());
360    /// let _ = tooltip;
361    /// ```
362    pub fn tooltip_style(mut self, style: TooltipStyle) -> Self {
363        self.style = style;
364        self
365    }
366}
367
368/// Component properties used to allocate one retained tooltip state machine.
369struct TooltipComponent<A> {
370    /// Outer logical sizing policy for the trigger child.
371    layout: LayoutStyle,
372    /// Static or reactive tooltip text.
373    content: TooltipContent,
374    /// Optional trigger view owning hover/focus interaction.
375    child: Option<View<A>>,
376    /// Preferred side of the trigger for popup placement.
377    placement: PopupPlacement,
378    /// Cross-axis alignment relative to the trigger.
379    alignment: PopupAlignment,
380    /// Reactive interaction-disable flag.
381    disabled: Binding<bool>,
382    /// Hover/focus dwell time before opening.
383    open_delay: Duration,
384    /// Grace period before closing after interaction leaves.
385    close_delay: Duration,
386    /// Logical-pixel separation from the trigger.
387    gap: f32,
388    /// Popup surface and text styling.
389    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)]
448/// Timing phase for hover-driven tooltip visibility.
449enum TooltipPhase {
450    /// Not painted and with no active deadline.
451    #[default]
452    Hidden,
453    /// Waiting until the stored instant before opening.
454    Opening(Instant),
455    /// Painted with no active deadline.
456    Open,
457    /// Still painted until the stored close deadline.
458    Closing(Instant),
459}
460
461impl TooltipPhase {
462    /// Returns whether popup geometry should currently be published.
463    fn is_painted(self) -> bool {
464        matches!(self, Self::Open | Self::Closing(_))
465    }
466}
467
468#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
469/// Retained focus, hover, dismissal, and timing state.
470struct TooltipState {
471    /// Current hover-driven timing phase.
472    phase: TooltipPhase,
473    /// Whether the trigger subtree is currently hovered.
474    hovered: bool,
475    /// Whether focus is currently within the trigger subtree.
476    focused: bool,
477    /// Suppresses reopening until hover leaves after explicit dismissal.
478    dismissed_until_hover_exit: bool,
479    /// Suppresses reopening until focus leaves after explicit dismissal.
480    dismissed_until_focus_exit: bool,
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484/// Widget-owned values published only after their exact layout attempt commits.
485struct TooltipLayoutCommit {
486    /// Whether authoritative trigger geometry is non-empty.
487    has_trigger: bool,
488    /// Whether unavailable content requires closing an existing portal mount.
489    close_portal: bool,
490}
491
492/// Retained portal owner and interaction state machine around the trigger child.
493struct TooltipWidget<A> {
494    /// Outer logical sizing policy for the trigger child.
495    layout: LayoutStyle,
496    /// Static or reactive tooltip text.
497    content: TooltipContent,
498    /// Preferred side of the trigger for popup placement.
499    placement: PopupPlacement,
500    /// Cross-axis alignment relative to the trigger.
501    alignment: PopupAlignment,
502    /// Reactive interaction-disable flag.
503    disabled: Binding<bool>,
504    /// Hover/focus dwell time before opening.
505    open_delay: Duration,
506    /// Grace period before closing after interaction leaves.
507    close_delay: Duration,
508    /// Logical-pixel separation from the trigger.
509    gap: f32,
510    /// Popup surface and text styling.
511    style: TooltipStyle,
512    /// Retained hover/focus deadlines and open state.
513    state: Signal<TooltipState>,
514    /// Retained element that owns popup lifecycle and focus semantics.
515    owner: ailloli_ui_core::ElementId,
516    /// UI-local runtime used to register and close portal content.
517    runtime: RuntimeHandle<A>,
518    /// Whether a trigger child received layout in the latest pass.
519    has_trigger: Cell<bool>,
520    /// Trigger availability and close effect staged for one layout attempt.
521    pending_layout: Cell<Option<TransactionalLayoutPending<TooltipLayoutCommit>>>,
522    /// Whether this widget currently has content mounted in the portal.
523    portal_presented: Signal<bool>,
524    /// Bridge that synchronizes retained popup content with the runtime registry.
525    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    /// Publishes trigger availability and applies close only after commit.
578    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            // Acts as a fallback for non-focusable triggers. A focusable child is
652            // selected first by the runtime's nearest-focusable routing.
653            FocusPolicy::Focusable
654        }
655    }
656}
657
658impl<A: 'static> TooltipWidget<A> {
659    /// Returns whether content, trigger geometry, and enabled state permit opening.
660    fn is_available(&self) -> bool {
661        !self.disabled.read() && self.has_trigger.get() && self.content.has_text()
662    }
663
664    /// Mirrors a host-side portal dismissal into local suppression state.
665    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    /// Applies immediate focus-open and blur-close transitions.
679    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    /// Applies hover transitions, resolves deadlines, and schedules repaint.
702    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    /// Resolves a due deadline and returns the current phase.
738    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    /// Requests owner repaint at a pending phase's deadline.
750    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    /// Commits state only when it changed, avoiding redundant invalidation.
760    fn update_state(&self, state: TooltipState) {
761        if self.state.read() != state {
762            self.state.set(state);
763        }
764    }
765
766    /// Hides the portal and optionally suppresses reopen until input exits.
767    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    /// Measures the retained content and publishes its resolved host geometry.
781    ///
782    /// Drawing is deliberately absent here: [`ailloli_ui_runtime::popup_mount::PopupOverlayMounts`] owns the
783    /// one retained paint of the bubble and its text.
784    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
823/// Creates an immediate or deadline-bearing open/close phase.
824fn 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
838/// Converts due opening/closing phases to their terminal phase.
839fn 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    //! Scenario coverage for defaults, zero-delay phases, close grace, and the
850    //! distinction between the window-root viewport and nested clips.
851
852    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}