Skip to main content

purple_ssh/
animation.rs

1use std::time::Instant;
2
3use ratatui::buffer::Buffer;
4
5use crate::app::{App, PingStatus, Screen};
6
7/// Braille spinner sequence for ping Checking status.
8pub const SPINNER_FRAMES: &[&str] = &[
9    "\u{280B}", // ⠋
10    "\u{2819}", // ⠙
11    "\u{2839}", // ⠹
12    "\u{2838}", // ⠸
13    "\u{283C}", // ⠼
14    "\u{2834}", // ⠴
15    "\u{2826}", // ⠦
16    "\u{2827}", // ⠧
17    "\u{2807}", // ⠇
18    "\u{280F}", // ⠏
19];
20
21/// Detail panel animation duration in milliseconds.
22const DETAIL_ANIM_DURATION_MS: u128 = 200;
23
24/// Overlay animation duration in milliseconds.
25const OVERLAY_ANIM_DURATION_MS: u128 = 250;
26
27/// Welcome overlay animation duration in milliseconds.
28const WELCOME_ANIM_DURATION_MS: u128 = 350;
29
30/// Active detail panel width animation.
31pub(crate) struct DetailAnim {
32    start: Instant,
33    opening: bool,
34    start_progress: f32,
35}
36
37/// Active overlay open/close animation.
38pub(crate) struct OverlayAnim {
39    pub(crate) start: Instant,
40    pub(crate) opening: bool,
41    pub(crate) duration_ms: u128,
42}
43
44/// Captured overlay state for close animation. Bundles the buffer snapshot with the
45/// dim flag so they are always in sync (the close animation knows whether to dim).
46pub(crate) struct OverlayCloseState {
47    pub(crate) buffer: Buffer,
48    pub(crate) dimmed: bool,
49}
50
51/// Animation state kept separate from App (render-layer concern).
52pub struct AnimationState {
53    pub spinner_tick: u64,
54    pub(crate) prev_was_overlay: bool,
55    pub(crate) detail_anim: Option<DetailAnim>,
56    pub(crate) overlay_anim: Option<OverlayAnim>,
57    /// Saved overlay state for close animation (captured once when overlay is stable).
58    pub(crate) overlay_close: Option<OverlayCloseState>,
59    /// Tunnels detail panel height animation. Triggered when the
60    /// selected tunnel changes its active state (or the user navigates
61    /// to a tunnel with a different state). Mirrors the host_list
62    /// detail-panel anim with the same 200ms cubic ease-out, but
63    /// scales panel HEIGHT instead of width.
64    pub(crate) tunnel_panel_anim: Option<DetailAnim>,
65    /// Last-frame visibility used to detect open/close transitions.
66    /// `None` means we have not observed any frame yet — the first
67    /// call seeds it without triggering an animation so a fresh
68    /// `AnimationState` does not flicker the panel into existence.
69    pub(crate) prev_tunnel_panel_visible: Option<bool>,
70}
71
72impl AnimationState {
73    pub fn new() -> Self {
74        Self {
75            spinner_tick: 0,
76            prev_was_overlay: false,
77            detail_anim: None,
78            overlay_anim: None,
79            overlay_close: None,
80            tunnel_panel_anim: None,
81            prev_tunnel_panel_visible: None,
82        }
83    }
84
85    /// Whether any animation is running.
86    pub fn is_animating(&self, app: &App) -> bool {
87        let welcome_animating = app
88            .ui
89            .welcome_opened
90            .is_some_and(|t| t.elapsed().as_millis() < 3000);
91        self.detail_anim.is_some()
92            || self.tunnel_panel_anim.is_some()
93            || self.overlay_anim.is_some()
94            || welcome_animating
95    }
96
97    /// Whether any host has PingStatus::Checking (spinner needs ticking).
98    pub fn has_checking_hosts(&self, app: &App) -> bool {
99        app.ping
100            .status_map()
101            .values()
102            .any(|s| matches!(s, PingStatus::Checking))
103    }
104
105    /// Whether any host is currently Reachable. Drives the "breathing"
106    /// pulse on online indicators: when at least one host is alive the
107    /// main loop runs at 80ms tick rate so `online_dot_pulsing` can
108    /// advance smoothly. Slow/Unreachable/Checking deliberately do NOT
109    /// pulse — only confirmed-online gets the subtle live signal.
110    pub fn has_reachable_hosts(&self, app: &App) -> bool {
111        app.ping
112            .status_map()
113            .values()
114            .any(|s| matches!(s, PingStatus::Reachable { .. }))
115    }
116
117    /// Advance spinner tick. Called from main loop at ~80ms intervals.
118    pub fn tick_spinner(&mut self) {
119        self.spinner_tick = self.spinner_tick.wrapping_add(1);
120    }
121
122    /// Current overlay animation progress (0.0 = hidden, 1.0 = fully visible).
123    pub fn overlay_anim_progress(&self) -> Option<f32> {
124        let anim = self.overlay_anim.as_ref()?;
125        let elapsed = anim.start.elapsed().as_millis();
126        if elapsed >= anim.duration_ms {
127            return None;
128        }
129        let t = elapsed as f32 / anim.duration_ms as f32;
130        let eased = 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t);
131        Some(if anim.opening { eased } else { 1.0 - eased })
132    }
133
134    /// Tick overlay animation: clean up when complete.
135    pub fn tick_overlay_anim(&mut self) {
136        if self.overlay_anim.is_some() && self.overlay_anim_progress().is_none() {
137            let was_closing = self.overlay_anim.as_ref().is_some_and(|a| !a.opening);
138            self.overlay_anim = None;
139            if was_closing {
140                self.overlay_close = None;
141            }
142        }
143    }
144
145    /// Current detail panel animation progress (0.0 = closed, 1.0 = open).
146    pub fn detail_anim_progress(&mut self) -> Option<f32> {
147        let anim = self.detail_anim.as_ref()?;
148        let elapsed = anim.start.elapsed().as_millis();
149        if elapsed >= DETAIL_ANIM_DURATION_MS {
150            self.detail_anim = None;
151            return None;
152        }
153        let t = elapsed as f32 / DETAIL_ANIM_DURATION_MS as f32;
154        let eased = 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t);
155        let progress = if anim.opening {
156            anim.start_progress + (1.0 - anim.start_progress) * eased
157        } else {
158            anim.start_progress * (1.0 - eased)
159        };
160        Some(progress)
161    }
162
163    /// Notify the animator that the tunnel detail panel target
164    /// visibility has been computed for this frame. Starts a slide
165    /// animation when the target flips, preserving the in-flight
166    /// progress so a flap mid-animation reverses smoothly.
167    pub fn note_tunnel_panel_target(&mut self, visible: bool) {
168        match self.prev_tunnel_panel_visible {
169            None => {
170                // First observation — no anim, just record state.
171                self.prev_tunnel_panel_visible = Some(visible);
172            }
173            Some(prev) if prev == visible => {}
174            Some(_) => {
175                let start_progress =
176                    self.tunnel_panel_anim_progress()
177                        .unwrap_or(if visible { 0.0 } else { 1.0 });
178                self.tunnel_panel_anim = Some(DetailAnim {
179                    start: Instant::now(),
180                    opening: visible,
181                    start_progress,
182                });
183                self.prev_tunnel_panel_visible = Some(visible);
184            }
185        }
186    }
187
188    /// Current tunnel-panel height animation progress
189    /// (0.0 = collapsed, 1.0 = full height). Returns `None` when no
190    /// animation is in flight.
191    pub fn tunnel_panel_anim_progress(&mut self) -> Option<f32> {
192        let anim = self.tunnel_panel_anim.as_ref()?;
193        let elapsed = anim.start.elapsed().as_millis();
194        if elapsed >= DETAIL_ANIM_DURATION_MS {
195            self.tunnel_panel_anim = None;
196            return None;
197        }
198        let t = elapsed as f32 / DETAIL_ANIM_DURATION_MS as f32;
199        let eased = 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t);
200        let progress = if anim.opening {
201            anim.start_progress + (1.0 - anim.start_progress) * eased
202        } else {
203            anim.start_progress * (1.0 - eased)
204        };
205        Some(progress)
206    }
207
208    /// Detect overlay open/close transitions and start animations.
209    pub fn detect_transitions(&mut self, app: &mut App) {
210        let is_overlay = !matches!(app.screen, Screen::HostList);
211
212        if is_overlay && !self.prev_was_overlay {
213            let is_welcome = matches!(app.screen, Screen::Welcome { .. });
214            if is_welcome {
215                app.ui.welcome_opened = Some(Instant::now());
216            }
217            self.overlay_anim = Some(OverlayAnim {
218                start: Instant::now(),
219                opening: true,
220                duration_ms: if is_welcome {
221                    WELCOME_ANIM_DURATION_MS
222                } else {
223                    OVERLAY_ANIM_DURATION_MS
224                },
225            });
226        } else if !is_overlay && self.prev_was_overlay {
227            if self.overlay_close.is_some() {
228                self.overlay_anim = Some(OverlayAnim {
229                    start: Instant::now(),
230                    opening: false,
231                    duration_ms: OVERLAY_ANIM_DURATION_MS,
232                });
233            }
234            app.ui.welcome_opened = None;
235        }
236
237        // Detail panel toggle. Branched on `top_page` so the same
238        // `v` keybinding drives the right view_mode for the active
239        // tab. Only one detail panel is animating at a time, so a
240        // single `detail_anim` slot suffices.
241        if app.ui.detail_toggle_pending {
242            app.ui.detail_toggle_pending = false;
243            let opening = match app.top_page {
244                crate::app::TopPage::Containers => {
245                    app.containers_overview.view_mode == crate::app::ViewMode::Detailed
246                }
247                _ => app.hosts_state.view_mode == crate::app::ViewMode::Detailed,
248            };
249            let start_progress =
250                self.detail_anim_progress()
251                    .unwrap_or(if opening { 0.0 } else { 1.0 });
252            self.detail_anim = Some(DetailAnim {
253                start: Instant::now(),
254                opening,
255                start_progress,
256            });
257        }
258
259        self.prev_was_overlay = is_overlay;
260    }
261}
262
263impl Default for AnimationState {
264    fn default() -> Self {
265        Self::new()
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use ratatui::layout::Rect;
272
273    use super::*;
274
275    fn make_app() -> App {
276        use std::path::PathBuf;
277        let config = crate::ssh_config::model::SshConfigFile {
278            elements: crate::ssh_config::model::SshConfigFile::parse_content(""),
279            path: PathBuf::from("/tmp/test_config"),
280            crlf: false,
281            bom: false,
282        };
283        App::new(config)
284    }
285
286    // --- Spinner tests ---
287
288    #[test]
289    fn spinner_frames_are_10() {
290        assert_eq!(SPINNER_FRAMES.len(), 10);
291    }
292
293    #[test]
294    fn spinner_frames_cycle_via_index() {
295        assert_eq!(SPINNER_FRAMES[0], "\u{280B}");
296        assert_eq!(SPINNER_FRAMES[1], "\u{2819}");
297        assert_eq!(SPINNER_FRAMES[10 % SPINNER_FRAMES.len()], "\u{280B}");
298    }
299
300    #[test]
301    fn spinner_frames_at_u64_max() {
302        let idx = (u64::MAX as usize) % SPINNER_FRAMES.len();
303        assert_eq!(SPINNER_FRAMES[idx], "\u{2834}");
304    }
305
306    #[test]
307    fn spinner_tick_wraps() {
308        let mut anim = AnimationState::new();
309        anim.spinner_tick = u64::MAX;
310        anim.tick_spinner();
311        assert_eq!(anim.spinner_tick, 0);
312    }
313
314    #[test]
315    fn spinner_tick_increments_by_one() {
316        let mut anim = AnimationState::new();
317        assert_eq!(anim.spinner_tick, 0);
318        anim.tick_spinner();
319        assert_eq!(anim.spinner_tick, 1);
320    }
321
322    // --- is_animating tests ---
323
324    #[test]
325    fn new_state_not_animating() {
326        let app = make_app();
327        let anim = AnimationState::new();
328        assert!(!anim.is_animating(&app));
329    }
330
331    #[test]
332    fn is_animating_with_overlay_anim() {
333        let mut app = make_app();
334        let mut anim = AnimationState::new();
335        app.screen = Screen::Help {
336            return_screen: Box::new(Screen::HostList),
337        };
338        anim.detect_transitions(&mut app);
339        assert!(anim.is_animating(&app));
340    }
341
342    #[test]
343    fn is_animating_with_detail_anim() {
344        let mut app = make_app();
345        let mut anim = AnimationState::new();
346        app.ui.detail_toggle_pending = true;
347        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
348        anim.detect_transitions(&mut app);
349        assert!(anim.is_animating(&app));
350    }
351
352    // --- has_checking_hosts tests ---
353
354    #[test]
355    fn has_checking_hosts_empty() {
356        let app = make_app();
357        let anim = AnimationState::new();
358        assert!(!anim.has_checking_hosts(&app));
359    }
360
361    #[test]
362    fn has_checking_hosts_only_reachable() {
363        let mut app = make_app();
364        app.ping
365            .insert_status("host1".to_string(), PingStatus::Reachable { rtt_ms: 10 });
366        app.ping
367            .insert_status("host2".to_string(), PingStatus::Unreachable);
368        let anim = AnimationState::new();
369        assert!(!anim.has_checking_hosts(&app));
370    }
371
372    #[test]
373    fn has_checking_hosts_with_checking() {
374        let mut app = make_app();
375        app.ping
376            .insert_status("host2".to_string(), PingStatus::Checking);
377        let anim = AnimationState::new();
378        assert!(anim.has_checking_hosts(&app));
379    }
380
381    // --- overlay animation tests ---
382
383    #[test]
384    fn detect_transitions_opens_overlay() {
385        let mut app = make_app();
386        let mut anim = AnimationState::new();
387        app.screen = Screen::Help {
388            return_screen: Box::new(Screen::HostList),
389        };
390        anim.detect_transitions(&mut app);
391        assert!(anim.prev_was_overlay);
392        assert!(anim.overlay_anim.is_some());
393        assert!(anim.overlay_anim.as_ref().unwrap().opening);
394    }
395
396    #[test]
397    fn detect_transitions_closes_overlay() {
398        let mut app = make_app();
399        let mut anim = AnimationState::new();
400        app.screen = Screen::Help {
401            return_screen: Box::new(Screen::HostList),
402        };
403        anim.detect_transitions(&mut app);
404        // Simulate saved buffer
405        anim.overlay_close = Some(OverlayCloseState {
406            buffer: Buffer::empty(Rect::new(0, 0, 80, 24)),
407            dimmed: true,
408        });
409
410        app.screen = Screen::HostList;
411        anim.detect_transitions(&mut app);
412        assert!(!anim.prev_was_overlay);
413        assert!(anim.overlay_anim.is_some());
414        assert!(!anim.overlay_anim.as_ref().unwrap().opening);
415    }
416
417    #[test]
418    fn overlay_close_without_buffer_skips_anim() {
419        let mut app = make_app();
420        let mut anim = AnimationState::new();
421        app.screen = Screen::Help {
422            return_screen: Box::new(Screen::HostList),
423        };
424        anim.detect_transitions(&mut app);
425        // No overlay_buffer saved
426
427        app.screen = Screen::HostList;
428        anim.detect_transitions(&mut app);
429        // No close animation without a saved buffer
430        assert!(anim.overlay_anim.is_none() || anim.overlay_anim.as_ref().unwrap().opening);
431    }
432
433    #[test]
434    fn overlay_anim_progress_returns_value() {
435        let mut app = make_app();
436        let mut anim = AnimationState::new();
437        app.screen = Screen::Help {
438            return_screen: Box::new(Screen::HostList),
439        };
440        anim.detect_transitions(&mut app);
441        let progress = anim.overlay_anim_progress();
442        assert!(progress.is_some());
443        assert!((0.0..=1.0).contains(&progress.unwrap()));
444    }
445
446    #[test]
447    fn tick_overlay_anim_clears_on_completion() {
448        let mut app = make_app();
449        let mut anim = AnimationState::new();
450        app.screen = Screen::Help {
451            return_screen: Box::new(Screen::HostList),
452        };
453        anim.detect_transitions(&mut app);
454        // Fast-forward
455        anim.overlay_anim.as_mut().unwrap().start =
456            Instant::now() - std::time::Duration::from_millis(500);
457        anim.tick_overlay_anim();
458        assert!(anim.overlay_anim.is_none());
459    }
460
461    #[test]
462    fn tick_overlay_close_clears_buffer() {
463        let mut app = make_app();
464        let mut anim = AnimationState::new();
465        app.screen = Screen::Help {
466            return_screen: Box::new(Screen::HostList),
467        };
468        anim.detect_transitions(&mut app);
469        anim.overlay_close = Some(OverlayCloseState {
470            buffer: Buffer::empty(Rect::new(0, 0, 80, 24)),
471            dimmed: true,
472        });
473
474        // Close
475        app.screen = Screen::HostList;
476        anim.detect_transitions(&mut app);
477        // Fast-forward close
478        anim.overlay_anim.as_mut().unwrap().start =
479            Instant::now() - std::time::Duration::from_millis(500);
480        anim.tick_overlay_anim();
481        assert!(anim.overlay_anim.is_none());
482        assert!(anim.overlay_close.is_none());
483    }
484
485    #[test]
486    fn detect_transitions_stable_hostlist_no_anim() {
487        let mut app = make_app();
488        let mut anim = AnimationState::new();
489        anim.detect_transitions(&mut app);
490        anim.detect_transitions(&mut app);
491        assert!(!anim.prev_was_overlay);
492        assert!(anim.overlay_anim.is_none());
493    }
494
495    #[test]
496    fn detect_transitions_welcome_sets_welcome_opened() {
497        let mut app = make_app();
498        let mut anim = AnimationState::new();
499        app.screen = Screen::Welcome {
500            has_backup: false,
501            host_count: 0,
502            known_hosts_count: 0,
503        };
504        anim.detect_transitions(&mut app);
505        assert!(app.ui.welcome_opened.is_some());
506        assert_eq!(
507            anim.overlay_anim.as_ref().unwrap().duration_ms,
508            WELCOME_ANIM_DURATION_MS
509        );
510    }
511
512    #[test]
513    fn detect_transitions_welcome_close_clears_welcome_opened() {
514        let mut app = make_app();
515        let mut anim = AnimationState::new();
516        app.screen = Screen::Welcome {
517            has_backup: false,
518            host_count: 0,
519            known_hosts_count: 0,
520        };
521        anim.detect_transitions(&mut app);
522        app.screen = Screen::HostList;
523        anim.detect_transitions(&mut app);
524        assert!(app.ui.welcome_opened.is_none());
525    }
526
527    #[test]
528    fn close_non_welcome_overlay_clears_welcome_opened() {
529        let mut app = make_app();
530        let mut anim = AnimationState::new();
531        app.ui.welcome_opened = Some(Instant::now());
532        app.screen = Screen::Help {
533            return_screen: Box::new(Screen::HostList),
534        };
535        anim.detect_transitions(&mut app);
536        app.screen = Screen::HostList;
537        anim.detect_transitions(&mut app);
538        assert!(app.ui.welcome_opened.is_none());
539    }
540
541    // --- detail animation tests ---
542
543    #[test]
544    fn detail_toggle_open_starts_anim() {
545        let mut app = make_app();
546        let mut anim = AnimationState::new();
547        app.ui.detail_toggle_pending = true;
548        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
549        anim.detect_transitions(&mut app);
550        assert!(!app.ui.detail_toggle_pending);
551        assert!(anim.detail_anim.is_some());
552    }
553
554    #[test]
555    fn detail_toggle_close_starts_anim() {
556        let mut app = make_app();
557        let mut anim = AnimationState::new();
558        app.ui.detail_toggle_pending = true;
559        app.hosts_state.view_mode = crate::app::ViewMode::Compact;
560        anim.detect_transitions(&mut app);
561        assert!(anim.detail_anim.is_some());
562    }
563
564    #[test]
565    fn detail_anim_progress_returns_value() {
566        let mut app = make_app();
567        let mut anim = AnimationState::new();
568        app.ui.detail_toggle_pending = true;
569        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
570        anim.detect_transitions(&mut app);
571        let p = anim.detail_anim_progress();
572        assert!(p.is_some());
573        assert!((0.0..=1.0).contains(&p.unwrap()));
574    }
575
576    #[test]
577    fn detail_anim_progress_none_when_no_anim() {
578        let mut anim = AnimationState::new();
579        assert!(anim.detail_anim_progress().is_none());
580    }
581
582    #[test]
583    fn detail_anim_completes_and_clears() {
584        let mut app = make_app();
585        let mut anim = AnimationState::new();
586        app.ui.detail_toggle_pending = true;
587        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
588        anim.detect_transitions(&mut app);
589        anim.detail_anim.as_mut().unwrap().start =
590            Instant::now() - std::time::Duration::from_millis(300);
591        assert!(anim.detail_anim_progress().is_none());
592        assert!(anim.detail_anim.is_none());
593    }
594
595    #[test]
596    fn detail_anim_reversal_mid_flight() {
597        let mut app = make_app();
598        let mut anim = AnimationState::new();
599        app.ui.detail_toggle_pending = true;
600        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
601        anim.detect_transitions(&mut app);
602        let _ = anim.detail_anim_progress();
603
604        app.ui.detail_toggle_pending = true;
605        app.hosts_state.view_mode = crate::app::ViewMode::Compact;
606        anim.detect_transitions(&mut app);
607        assert!(anim.detail_anim.is_some());
608        assert!(!anim.detail_anim.as_ref().unwrap().opening);
609    }
610
611    #[test]
612    fn detail_anim_independent_of_overlay() {
613        let mut app = make_app();
614        let mut anim = AnimationState::new();
615        app.ui.detail_toggle_pending = true;
616        app.hosts_state.view_mode = crate::app::ViewMode::Detailed;
617        app.screen = Screen::Help {
618            return_screen: Box::new(Screen::HostList),
619        };
620        anim.detect_transitions(&mut app);
621        assert!(anim.detail_anim.is_some());
622        assert!(anim.overlay_anim.is_some());
623    }
624
625    #[test]
626    fn overlay_close_state_initially_none() {
627        let anim = AnimationState::new();
628        assert!(anim.overlay_close.is_none());
629    }
630}