tooltip.rs

  1use super::{
  2    ContainerStyle, Drawable, Element, Flex, KeystrokeLabel, MouseEventHandler, Overlay,
  3    OverlayFitMode, ParentElement, Text,
  4};
  5use crate::{
  6    fonts::TextStyle,
  7    geometry::{rect::RectF, vector::Vector2F},
  8    json::json,
  9    Action, Axis, ElementStateHandle, SceneBuilder, SizeConstraint, Task, View, ViewContext,
 10};
 11use serde::Deserialize;
 12use std::{
 13    cell::{Cell, RefCell},
 14    ops::Range,
 15    rc::Rc,
 16    time::Duration,
 17};
 18
 19const DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(500);
 20
 21pub struct Tooltip<V: View> {
 22    child: Element<V>,
 23    tooltip: Option<Element<V>>,
 24    _state: ElementStateHandle<Rc<TooltipState>>,
 25}
 26
 27#[derive(Default)]
 28struct TooltipState {
 29    visible: Cell<bool>,
 30    position: Cell<Vector2F>,
 31    debounce: RefCell<Option<Task<()>>>,
 32}
 33
 34#[derive(Clone, Deserialize, Default)]
 35pub struct TooltipStyle {
 36    #[serde(flatten)]
 37    pub container: ContainerStyle,
 38    pub text: TextStyle,
 39    keystroke: KeystrokeStyle,
 40    pub max_text_width: f32,
 41}
 42
 43#[derive(Clone, Deserialize, Default)]
 44pub struct KeystrokeStyle {
 45    #[serde(flatten)]
 46    container: ContainerStyle,
 47    #[serde(flatten)]
 48    text: TextStyle,
 49}
 50
 51impl<V: View> Tooltip<V> {
 52    pub fn new<Tag: 'static, T: View>(
 53        id: usize,
 54        text: String,
 55        action: Option<Box<dyn Action>>,
 56        style: TooltipStyle,
 57        child: Element<V>,
 58        cx: &mut ViewContext<V>,
 59    ) -> Self {
 60        struct ElementState<Tag>(Tag);
 61        struct MouseEventHandlerState<Tag>(Tag);
 62        let focused_view_id = cx.focused_view_id();
 63
 64        let state_handle = cx.default_element_state::<ElementState<Tag>, Rc<TooltipState>>(id);
 65        let state = state_handle.read(cx).clone();
 66        let tooltip = if state.visible.get() {
 67            let mut collapsed_tooltip = Self::render_tooltip(
 68                focused_view_id,
 69                text.clone(),
 70                style.clone(),
 71                action.as_ref().map(|a| a.boxed_clone()),
 72                true,
 73            )
 74            .boxed();
 75            Some(
 76                Overlay::new(
 77                    Self::render_tooltip(focused_view_id, text, style, action, false)
 78                        .constrained()
 79                        .dynamically(move |constraint, view, cx| {
 80                            SizeConstraint::strict_along(
 81                                Axis::Vertical,
 82                                collapsed_tooltip.layout(constraint, view, cx).y(),
 83                            )
 84                        })
 85                        .boxed(),
 86                )
 87                .with_fit_mode(OverlayFitMode::SwitchAnchor)
 88                .with_anchor_position(state.position.get())
 89                .boxed(),
 90            )
 91        } else {
 92            None
 93        };
 94        let child = MouseEventHandler::<MouseEventHandlerState<Tag>, _>::new(id, cx, |_, _| child)
 95            .on_hover(move |e, _, cx| {
 96                let position = e.position;
 97                let window_id = cx.window_id();
 98                let view_id = cx.view_id();
 99                if e.started {
100                    if !state.visible.get() {
101                        state.position.set(position);
102
103                        let mut debounce = state.debounce.borrow_mut();
104                        if debounce.is_none() {
105                            *debounce = Some(cx.spawn({
106                                let state = state.clone();
107                                |_, mut cx| async move {
108                                    cx.background().timer(DEBOUNCE_TIMEOUT).await;
109                                    state.visible.set(true);
110                                    cx.update(|cx| cx.notify_view(window_id, view_id));
111                                }
112                            }));
113                        }
114                    }
115                } else {
116                    state.visible.set(false);
117                    state.debounce.take();
118                    cx.notify();
119                }
120            })
121            .boxed();
122        Self {
123            child,
124            tooltip,
125            _state: state_handle,
126        }
127    }
128
129    pub fn render_tooltip(
130        focused_view_id: Option<usize>,
131        text: String,
132        style: TooltipStyle,
133        action: Option<Box<dyn Action>>,
134        measure: bool,
135    ) -> impl Drawable<V> {
136        Flex::row()
137            .with_child({
138                let text = Text::new(text, style.text)
139                    .constrained()
140                    .with_max_width(style.max_text_width);
141                if measure {
142                    text.flex(1., false).boxed()
143                } else {
144                    text.flex(1., false).aligned().boxed()
145                }
146            })
147            .with_children(action.and_then(|action| {
148                let keystroke_label = KeystrokeLabel::new(
149                    focused_view_id?,
150                    action,
151                    style.keystroke.container,
152                    style.keystroke.text,
153                );
154                if measure {
155                    Some(keystroke_label.boxed())
156                } else {
157                    Some(keystroke_label.aligned().boxed())
158                }
159            }))
160            .contained()
161            .with_style(style.container)
162    }
163}
164
165impl<V: View> Drawable<V> for Tooltip<V> {
166    type LayoutState = ();
167    type PaintState = ();
168
169    fn layout(
170        &mut self,
171        constraint: SizeConstraint,
172        view: &mut V,
173        cx: &mut ViewContext<V>,
174    ) -> (Vector2F, Self::LayoutState) {
175        let size = self.child.layout(constraint, view, cx);
176        if let Some(tooltip) = self.tooltip.as_mut() {
177            tooltip.layout(
178                SizeConstraint::new(Vector2F::zero(), cx.window_size()),
179                view,
180                cx,
181            );
182        }
183        (size, ())
184    }
185
186    fn paint(
187        &mut self,
188        scene: &mut SceneBuilder,
189        bounds: RectF,
190        visible_bounds: RectF,
191        _: &mut Self::LayoutState,
192        view: &mut V,
193        cx: &mut ViewContext<V>,
194    ) {
195        self.child
196            .paint(scene, bounds.origin(), visible_bounds, view, cx);
197        if let Some(tooltip) = self.tooltip.as_mut() {
198            tooltip.paint(scene, bounds.origin(), visible_bounds, view, cx);
199        }
200    }
201
202    fn rect_for_text_range(
203        &self,
204        range: Range<usize>,
205        _: RectF,
206        _: RectF,
207        _: &Self::LayoutState,
208        _: &Self::PaintState,
209        view: &V,
210        cx: &ViewContext<V>,
211    ) -> Option<RectF> {
212        self.child.rect_for_text_range(range, view, cx)
213    }
214
215    fn debug(
216        &self,
217        _: RectF,
218        _: &Self::LayoutState,
219        _: &Self::PaintState,
220        view: &V,
221        cx: &ViewContext<V>,
222    ) -> serde_json::Value {
223        json!({
224            "child": self.child.debug(view, cx),
225            "tooltip": self.tooltip.as_ref().map(|t| t.debug(view, cx)),
226        })
227    }
228}