use std::time::Duration;
use super::popup::CLOSED_LAYER;
use super::store::NodeKey;
use super::widgets::WidgetKind;
use super::{Behavior, InputMode, KeySource, NavInput, ROOT_KEY, Response, Ui};
use crate::widget::PointerInput;
pub const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
pub const TOOLTIP_RESHOW_DIVISOR: u32 = 5;
pub const TOOLTIP_AUTOPOP_FACTOR: u32 = 10;
pub(super) const TOOLTIP_LAYER: usize = CLOSED_LAYER - 1;
#[derive(Debug)]
pub(super) struct TooltipState {
delay: Duration,
subject: Option<NodeKey>,
since: Option<Duration>,
dismissed: bool,
quick: bool,
last_shown: Option<Duration>,
pub built: Option<(usize, usize)>,
}
impl Default for TooltipState {
fn default() -> Self {
Self {
delay: TOOLTIP_DELAY,
subject: None,
since: None,
dismissed: false,
quick: false,
last_shown: None,
built: None,
}
}
}
impl Ui {
pub fn tooltip(&mut self, anchor: &Response, text: &str) -> Option<Response> {
let slot = self.store.find(anchor.key)?;
self.store.get_mut(slot).tooltip = true;
let state = &mut self.tooltip;
if state.subject != Some(anchor.key) || state.dismissed || state.built.is_some() {
return None;
}
let since = *state.since.get_or_insert(self.text_clock);
let wait = if state.quick {
state.delay / TOOLTIP_RESHOW_DIVISOR
} else {
state.delay
};
let held = self.text_clock.saturating_sub(since);
if held < wait {
return None;
}
if held >= wait + state.delay * TOOLTIP_AUTOPOP_FACTOR {
state.dismissed = true;
return None;
}
state.last_shown = Some(self.text_clock);
let anchor_index = self.nodes.iter().rposition(|node| node.key == anchor.key)?;
let (index, response) = self.open_root(
Self::tooltip_key(anchor.key),
"tooltip",
&[],
Behavior::NONE,
|ui| {
ui.span("", text, &[]);
},
);
self.tooltip.built = Some((index, anchor_index));
self.mark(response.key, WidgetKind::Tooltip);
Some(response)
}
#[must_use]
pub fn tooltip_key(anchor: NodeKey) -> NodeKey {
Self::key_under(ROOT_KEY, KeySource::Tooltip(anchor.0))
}
pub fn set_tooltip_delay(&mut self, delay: Duration) {
self.tooltip.delay = delay;
}
pub fn dismiss_tooltip(&mut self) {
self.tooltip.dismissed = true;
}
pub(super) fn resolve_tooltip(&mut self, pointer: PointerInput, nav: NavInput) {
self.tooltip.built = None;
let subject = match self.focus.mode {
InputMode::Pointer => self
.store
.iter()
.filter(|node| node.tooltip && node.interaction.hovered)
.max_by_key(|node| node.stacking())
.map(|node| node.key),
InputMode::Navigation => self
.focused()
.filter(|&key| self.store.by_key(key).is_some_and(|node| node.tooltip)),
};
let state = &mut self.tooltip;
if subject != state.subject {
state.subject = subject;
state.since = None;
state.dismissed = false;
state.quick = state
.last_shown
.is_some_and(|shown| self.text_clock.saturating_sub(shown) <= state.delay);
}
if pointer.down || pointer.secondary_pressed || nav.accept || nav.menu {
state.dismissed = true;
}
}
}