tooltip.rs

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