freya_components/
tooltip.rs

1use std::borrow::Cow;
2
3use freya_animation::{
4    easing::Function,
5    hook::{
6        AnimatedValue,
7        Ease,
8        OnChange,
9        OnCreation,
10        ReadAnimatedValue,
11        use_animation,
12    },
13    prelude::AnimNum,
14};
15use freya_core::prelude::*;
16use torin::{
17    prelude::{
18        Alignment,
19        Area,
20        Direction,
21    },
22    size::Size,
23};
24
25use crate::{
26    get_theme,
27    theming::component_themes::{
28        TooltipTheme,
29        TooltipThemePartial,
30    },
31};
32
33/// Tooltip component.
34///
35/// # Example
36///
37/// ```rust
38/// # use freya::prelude::*;
39/// fn app() -> impl IntoElement {
40///     Tooltip::new("Hello, World!")
41/// }
42///
43/// # use freya_testing::prelude::*;
44/// # launch_doc(|| {
45/// #   rect().center().expanded().child(app())
46/// # }, (250., 250.).into(), "./images/gallery_tooltip.png");
47/// ```
48///
49/// # Preview
50/// ![Tooltip Preview][tooltip]
51#[cfg_attr(feature = "docs",
52    doc = embed_doc_image::embed_image!("tooltip", "images/gallery_tooltip.png")
53)]
54#[derive(PartialEq, Clone)]
55pub struct Tooltip {
56    /// Theme override.
57    pub(crate) theme: Option<TooltipThemePartial>,
58    /// Text to show in the [Tooltip].
59    text: Cow<'static, str>,
60    key: DiffKey,
61}
62
63impl KeyExt for Tooltip {
64    fn write_key(&mut self) -> &mut DiffKey {
65        &mut self.key
66    }
67}
68
69impl Tooltip {
70    pub fn new(text: impl Into<Cow<'static, str>>) -> Self {
71        Self {
72            theme: None,
73            text: text.into(),
74            key: DiffKey::None,
75        }
76    }
77}
78
79impl Render for Tooltip {
80    fn render(&self) -> impl IntoElement {
81        let theme = get_theme!(&self.theme, tooltip);
82        let TooltipTheme {
83            background,
84            color,
85            border_fill,
86        } = theme;
87
88        rect()
89            .padding((4., 10.))
90            .border(
91                Border::new()
92                    .width(1.)
93                    .alignment(BorderAlignment::Inner)
94                    .fill(border_fill),
95            )
96            .background(background)
97            .corner_radius(8.)
98            .child(
99                label()
100                    .max_lines(1)
101                    .font_size(14.)
102                    .color(color)
103                    .text(self.text.clone()),
104            )
105    }
106
107    fn render_key(&self) -> DiffKey {
108        self.key.clone().or(self.default_key())
109    }
110}
111
112#[derive(PartialEq, Clone, Copy, Debug, Default)]
113pub enum TooltipPosition {
114    Besides,
115    #[default]
116    Below,
117}
118
119#[derive(PartialEq)]
120pub struct TooltipContainer {
121    tooltip: Tooltip,
122    children: Vec<Element>,
123    position: TooltipPosition,
124    key: DiffKey,
125}
126
127impl KeyExt for TooltipContainer {
128    fn write_key(&mut self) -> &mut DiffKey {
129        &mut self.key
130    }
131}
132
133impl ChildrenExt for TooltipContainer {
134    fn get_children(&mut self) -> &mut Vec<Element> {
135        &mut self.children
136    }
137}
138
139impl TooltipContainer {
140    pub fn new(tooltip: Tooltip) -> Self {
141        Self {
142            tooltip,
143            children: vec![],
144            position: TooltipPosition::Below,
145            key: DiffKey::None,
146        }
147    }
148
149    pub fn position(mut self, position: TooltipPosition) -> Self {
150        self.position = position;
151        self
152    }
153}
154
155impl Render for TooltipContainer {
156    fn render(&self) -> impl IntoElement {
157        let mut is_hovering = use_state(|| false);
158        let mut size = use_state(Area::default);
159
160        let animation = use_animation(move |conf| {
161            conf.on_change(OnChange::Rerun);
162            conf.on_creation(OnCreation::Finish);
163
164            let scale = AnimNum::new(0.8, 1.)
165                .time(350)
166                .ease(Ease::Out)
167                .function(Function::Expo);
168            let opacity = AnimNum::new(0., 1.)
169                .time(350)
170                .ease(Ease::Out)
171                .function(Function::Expo);
172
173            if is_hovering() {
174                (scale, opacity)
175            } else {
176                (scale.into_reversed(), opacity.into_reversed())
177            }
178        });
179
180        let (scale, opacity) = animation.read().value();
181
182        let on_pointer_enter = move |_| {
183            is_hovering.set(true);
184        };
185
186        let on_pointer_leave = move |_| {
187            is_hovering.set(false);
188        };
189
190        let on_sized = move |e: Event<SizedEventData>| {
191            size.set(e.area);
192        };
193
194        let direction = match self.position {
195            TooltipPosition::Below => Direction::vertical(),
196            TooltipPosition::Besides => Direction::horizontal(),
197        };
198
199        rect()
200            .direction(direction)
201            .on_sized(on_sized)
202            .on_pointer_enter(on_pointer_enter)
203            .on_pointer_leave(on_pointer_leave)
204            .children(self.children.clone())
205            .child(
206                rect()
207                    .width(Size::px(0.))
208                    .height(Size::px(0.))
209                    .layer(1500)
210                    .opacity(opacity)
211                    .overflow(if opacity == 0. {
212                        Overflow::Clip
213                    } else {
214                        Overflow::None
215                    })
216                    .child({
217                        match self.position {
218                            TooltipPosition::Below => rect()
219                                .width(Size::px(size.read().width()))
220                                .cross_align(Alignment::Center)
221                                .main_align(Alignment::Center)
222                                .scale(scale)
223                                .padding((5., 0., 0., 0.))
224                                .child(self.tooltip.clone()),
225                            TooltipPosition::Besides => rect()
226                                .height(Size::px(size.read().height()))
227                                .cross_align(Alignment::Center)
228                                .main_align(Alignment::Center)
229                                .scale(scale)
230                                .padding((0., 0., 0., 5.))
231                                .child(self.tooltip.clone()),
232                        }
233                    }),
234            )
235    }
236
237    fn render_key(&self) -> DiffKey {
238        self.key.clone().or(self.default_key())
239    }
240}