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.set_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.set_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.set_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.set_detail_toggle_pending(true);
347        app.hosts_state
348            .set_view_mode(crate::app::ViewMode::Detailed);
349        anim.detect_transitions(&mut app);
350        assert!(anim.is_animating(&app));
351    }
352
353    // --- has_checking_hosts tests ---
354
355    #[test]
356    fn has_checking_hosts_empty() {
357        let app = make_app();
358        let anim = AnimationState::new();
359        assert!(!anim.has_checking_hosts(&app));
360    }
361
362    #[test]
363    fn has_checking_hosts_only_reachable() {
364        let mut app = make_app();
365        app.ping
366            .insert_status("host1".to_string(), PingStatus::Reachable { rtt_ms: 10 });
367        app.ping
368            .insert_status("host2".to_string(), PingStatus::Unreachable);
369        let anim = AnimationState::new();
370        assert!(!anim.has_checking_hosts(&app));
371    }
372
373    #[test]
374    fn has_checking_hosts_with_checking() {
375        let mut app = make_app();
376        app.ping
377            .insert_status("host2".to_string(), PingStatus::Checking);
378        let anim = AnimationState::new();
379        assert!(anim.has_checking_hosts(&app));
380    }
381
382    // --- overlay animation tests ---
383
384    #[test]
385    fn detect_transitions_opens_overlay() {
386        let mut app = make_app();
387        let mut anim = AnimationState::new();
388        app.screen = Screen::Help {
389            return_screen: Box::new(Screen::HostList),
390        };
391        anim.detect_transitions(&mut app);
392        assert!(anim.prev_was_overlay);
393        assert!(anim.overlay_anim.is_some());
394        assert!(anim.overlay_anim.as_ref().unwrap().opening);
395    }
396
397    #[test]
398    fn detect_transitions_closes_overlay() {
399        let mut app = make_app();
400        let mut anim = AnimationState::new();
401        app.screen = Screen::Help {
402            return_screen: Box::new(Screen::HostList),
403        };
404        anim.detect_transitions(&mut app);
405        // Simulate saved buffer
406        anim.overlay_close = Some(OverlayCloseState {
407            buffer: Buffer::empty(Rect::new(0, 0, 80, 24)),
408            dimmed: true,
409        });
410
411        app.screen = Screen::HostList;
412        anim.detect_transitions(&mut app);
413        assert!(!anim.prev_was_overlay);
414        assert!(anim.overlay_anim.is_some());
415        assert!(!anim.overlay_anim.as_ref().unwrap().opening);
416    }
417
418    #[test]
419    fn overlay_close_without_buffer_skips_anim() {
420        let mut app = make_app();
421        let mut anim = AnimationState::new();
422        app.screen = Screen::Help {
423            return_screen: Box::new(Screen::HostList),
424        };
425        anim.detect_transitions(&mut app);
426        // No overlay_buffer saved
427
428        app.screen = Screen::HostList;
429        anim.detect_transitions(&mut app);
430        // No close animation without a saved buffer
431        assert!(anim.overlay_anim.is_none() || anim.overlay_anim.as_ref().unwrap().opening);
432    }
433
434    #[test]
435    fn overlay_anim_progress_returns_value() {
436        let mut app = make_app();
437        let mut anim = AnimationState::new();
438        app.screen = Screen::Help {
439            return_screen: Box::new(Screen::HostList),
440        };
441        anim.detect_transitions(&mut app);
442        let progress = anim.overlay_anim_progress();
443        assert!(progress.is_some());
444        assert!((0.0..=1.0).contains(&progress.unwrap()));
445    }
446
447    #[test]
448    fn tick_overlay_anim_clears_on_completion() {
449        let mut app = make_app();
450        let mut anim = AnimationState::new();
451        app.screen = Screen::Help {
452            return_screen: Box::new(Screen::HostList),
453        };
454        anim.detect_transitions(&mut app);
455        // Fast-forward
456        anim.overlay_anim.as_mut().unwrap().start =
457            Instant::now() - std::time::Duration::from_millis(500);
458        anim.tick_overlay_anim();
459        assert!(anim.overlay_anim.is_none());
460    }
461
462    #[test]
463    fn tick_overlay_close_clears_buffer() {
464        let mut app = make_app();
465        let mut anim = AnimationState::new();
466        app.screen = Screen::Help {
467            return_screen: Box::new(Screen::HostList),
468        };
469        anim.detect_transitions(&mut app);
470        anim.overlay_close = Some(OverlayCloseState {
471            buffer: Buffer::empty(Rect::new(0, 0, 80, 24)),
472            dimmed: true,
473        });
474
475        // Close
476        app.screen = Screen::HostList;
477        anim.detect_transitions(&mut app);
478        // Fast-forward close
479        anim.overlay_anim.as_mut().unwrap().start =
480            Instant::now() - std::time::Duration::from_millis(500);
481        anim.tick_overlay_anim();
482        assert!(anim.overlay_anim.is_none());
483        assert!(anim.overlay_close.is_none());
484    }
485
486    #[test]
487    fn detect_transitions_stable_hostlist_no_anim() {
488        let mut app = make_app();
489        let mut anim = AnimationState::new();
490        anim.detect_transitions(&mut app);
491        anim.detect_transitions(&mut app);
492        assert!(!anim.prev_was_overlay);
493        assert!(anim.overlay_anim.is_none());
494    }
495
496    #[test]
497    fn detect_transitions_welcome_sets_welcome_opened() {
498        let mut app = make_app();
499        let mut anim = AnimationState::new();
500        app.screen = Screen::Welcome {
501            has_backup: false,
502            host_count: 0,
503            known_hosts_count: 0,
504        };
505        anim.detect_transitions(&mut app);
506        assert!(app.ui.welcome_opened().is_some());
507        assert_eq!(
508            anim.overlay_anim.as_ref().unwrap().duration_ms,
509            WELCOME_ANIM_DURATION_MS
510        );
511    }
512
513    #[test]
514    fn detect_transitions_welcome_close_clears_welcome_opened() {
515        let mut app = make_app();
516        let mut anim = AnimationState::new();
517        app.screen = Screen::Welcome {
518            has_backup: false,
519            host_count: 0,
520            known_hosts_count: 0,
521        };
522        anim.detect_transitions(&mut app);
523        app.screen = Screen::HostList;
524        anim.detect_transitions(&mut app);
525        assert!(app.ui.welcome_opened().is_none());
526    }
527
528    #[test]
529    fn close_non_welcome_overlay_clears_welcome_opened() {
530        let mut app = make_app();
531        let mut anim = AnimationState::new();
532        app.ui.set_welcome_opened(Some(Instant::now()));
533        app.screen = Screen::Help {
534            return_screen: Box::new(Screen::HostList),
535        };
536        anim.detect_transitions(&mut app);
537        app.screen = Screen::HostList;
538        anim.detect_transitions(&mut app);
539        assert!(app.ui.welcome_opened().is_none());
540    }
541
542    // --- detail animation tests ---
543
544    #[test]
545    fn detail_toggle_open_starts_anim() {
546        let mut app = make_app();
547        let mut anim = AnimationState::new();
548        app.ui.set_detail_toggle_pending(true);
549        app.hosts_state
550            .set_view_mode(crate::app::ViewMode::Detailed);
551        anim.detect_transitions(&mut app);
552        assert!(!app.ui.detail_toggle_pending());
553        assert!(anim.detail_anim.is_some());
554    }
555
556    #[test]
557    fn detail_toggle_close_starts_anim() {
558        let mut app = make_app();
559        let mut anim = AnimationState::new();
560        app.ui.set_detail_toggle_pending(true);
561        app.hosts_state.set_view_mode(crate::app::ViewMode::Compact);
562        anim.detect_transitions(&mut app);
563        assert!(anim.detail_anim.is_some());
564    }
565
566    #[test]
567    fn detail_anim_progress_returns_value() {
568        let mut app = make_app();
569        let mut anim = AnimationState::new();
570        app.ui.set_detail_toggle_pending(true);
571        app.hosts_state
572            .set_view_mode(crate::app::ViewMode::Detailed);
573        anim.detect_transitions(&mut app);
574        let p = anim.detail_anim_progress();
575        assert!(p.is_some());
576        assert!((0.0..=1.0).contains(&p.unwrap()));
577    }
578
579    #[test]
580    fn detail_anim_progress_none_when_no_anim() {
581        let mut anim = AnimationState::new();
582        assert!(anim.detail_anim_progress().is_none());
583    }
584
585    #[test]
586    fn detail_anim_completes_and_clears() {
587        let mut app = make_app();
588        let mut anim = AnimationState::new();
589        app.ui.set_detail_toggle_pending(true);
590        app.hosts_state
591            .set_view_mode(crate::app::ViewMode::Detailed);
592        anim.detect_transitions(&mut app);
593        anim.detail_anim.as_mut().unwrap().start =
594            Instant::now() - std::time::Duration::from_millis(300);
595        assert!(anim.detail_anim_progress().is_none());
596        assert!(anim.detail_anim.is_none());
597    }
598
599    #[test]
600    fn detail_anim_reversal_mid_flight() {
601        let mut app = make_app();
602        let mut anim = AnimationState::new();
603        app.ui.set_detail_toggle_pending(true);
604        app.hosts_state
605            .set_view_mode(crate::app::ViewMode::Detailed);
606        anim.detect_transitions(&mut app);
607        let _ = anim.detail_anim_progress();
608
609        app.ui.set_detail_toggle_pending(true);
610        app.hosts_state.set_view_mode(crate::app::ViewMode::Compact);
611        anim.detect_transitions(&mut app);
612        assert!(anim.detail_anim.is_some());
613        assert!(!anim.detail_anim.as_ref().unwrap().opening);
614    }
615
616    #[test]
617    fn detail_anim_independent_of_overlay() {
618        let mut app = make_app();
619        let mut anim = AnimationState::new();
620        app.ui.set_detail_toggle_pending(true);
621        app.hosts_state
622            .set_view_mode(crate::app::ViewMode::Detailed);
623        app.screen = Screen::Help {
624            return_screen: Box::new(Screen::HostList),
625        };
626        anim.detect_transitions(&mut app);
627        assert!(anim.detail_anim.is_some());
628        assert!(anim.overlay_anim.is_some());
629    }
630
631    #[test]
632    fn overlay_close_state_initially_none() {
633        let anim = AnimationState::new();
634        assert!(anim.overlay_close.is_none());
635    }
636}