freya_components/
cursor_blink.rs

1use std::time::Duration;
2
3use freya_animation::prelude::*;
4use freya_core::prelude::Color;
5use freya_sdk::timeout::*;
6
7// Duration of the animation
8const ANIMATION_TIME: Duration = Duration::from_millis(100);
9// Delay between animations
10const WAIT_ANIMATION_TIME: Duration = Duration::from_millis(750);
11// Time until the animation is started since the last reset (key down, mouse click)
12const ANIMATION_TIMEOUT: Duration = Duration::from_millis(500);
13
14/// A hook that manages the cursor blink animation with a typing timeout.
15/// When the user types, the cursor stays visible. After the timeout elapses,
16/// the cursor starts blinking again.
17pub fn use_cursor_blink(enable: bool, color: Color) -> (Timeout, Color) {
18    let movement_timeout = use_timeout(|| ANIMATION_TIMEOUT);
19
20    let cursor_blink = use_animation_with_dependencies(
21        &(enable, movement_timeout.elapsed()),
22        |conf, (enable, movement_elapsed)| {
23            // Only animate it when focused and there has been no recent movement
24            // If that's not the case, then it will be reset to the initial value,
25            // 255, and thus show statically
26            if *enable && *movement_elapsed {
27                conf.on_creation(OnCreation::Run);
28                conf.on_change(OnChange::Rerun);
29                conf.on_finish(OnFinish::reverse_with_delay(WAIT_ANIMATION_TIME));
30            }
31            AnimNum::new(255., 0.).duration(ANIMATION_TIME)
32        },
33    );
34
35    let cursor_color = color.with_a(cursor_blink.get().value() as u8);
36
37    (movement_timeout, cursor_color)
38}