Skip to main content

day_core/
testing.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Opt-in presentation policy for functional walkthroughs: fast mode is reduced motion forced
5//! on (docs/accessibility.md), nothing more. This is not a virtual clock: timers, network
6//! requests, physics and media retain their real timing.
7
8static FORCED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9
10/// Whether the launch forced reduced motion: `DAY_TEST_FAST=1` (`day launch --fast`) or
11/// `DAY_REDUCE_MOTION=1`, the override that lets a script or a screenshot run the reduced
12/// variant without the system setting. Neither is read after launch, and the user's own
13/// setting is OR-ed in by [`crate::reduce_motion_now`].
14pub(crate) fn forced_reduce_motion() -> bool {
15    *FORCED.get_or_init(|| {
16        let on = |key: &str| std::env::var(key).as_deref() == Ok("1");
17        on("DAY_TEST_FAST") || on("DAY_REDUCE_MOTION")
18    })
19}
20
21/// Skip decorative motion, applying its destination state immediately: the reduced-motion
22/// gate ([`crate::reduce_motion_now`]), which fast mode forces on. Kept under this name for
23/// the backends that ask it before animating a native transition.
24#[must_use]
25pub fn fast_animations() -> bool {
26    crate::reduce_motion_now()
27}
28
29/// Browser hosts have no process environment. Initialize once before constructing the UI.
30#[cfg(target_arch = "wasm32")]
31pub fn init_fast_animations(enabled: bool) {
32    let _ = FORCED.set(enabled);
33}
34
35#[cfg(test)]
36mod tests {
37    use crate::frame::{FrameClock, install_frame_requester};
38    use crate::tween::{Timing, Tweened, animate};
39    use day_spec::{AnimSpec, FrameStamp};
40    use std::{cell::RefCell, collections::VecDeque, rc::Rc};
41
42    #[test]
43    fn fast_motion_preserves_endpoints_and_continuous_clocks() {
44        // Exercise both startup policies in isolated processes, without racing other
45        // tests over a process-global environment variable or the cached policy.
46        if std::env::var_os("DAY_MOTION_TEST_CHILD").is_none() {
47            for fast in ["0", "1"] {
48                assert!(
49                    std::process::Command::new(std::env::current_exe().unwrap())
50                        .args([
51                            "--exact",
52                            "testing::tests::fast_motion_preserves_endpoints_and_continuous_clocks"
53                        ])
54                        .env("DAY_MOTION_TEST_CHILD", "1")
55                        .env("DAY_TEST_FAST", fast)
56                        .status()
57                        .unwrap()
58                        .success()
59                );
60            }
61            return;
62        }
63        let fast = super::fast_animations();
64        let pending = Rc::new(RefCell::new(VecDeque::new()));
65        let q = pending.clone();
66        install_frame_requester(move |_, cb| {
67            q.borrow_mut().push_back(cb);
68            Box::new(|| {})
69        });
70        let clock = FrameClock::for_root(crate::RNode::default());
71        let tween = Tweened::on(clock, 0.0);
72        tween.animate_to(42.0, AnimSpec::linear(1000));
73        assert_eq!(tween.get_untracked(), if fast { 42.0 } else { 0.0 });
74        let samples = Rc::new(RefCell::new(Vec::new()));
75        let s = samples.clone();
76        let finite = animate(
77            clock,
78            Timing::new(AnimSpec {
79                repeat: 1,
80                autoreverse: true,
81                delay_ms: 500,
82                ..AnimSpec::linear(1000)
83            }),
84            move |sample| s.borrow_mut().push(sample),
85        );
86        let continuous = clock.subscribe(|_| std::ops::ControlFlow::Continue(()));
87        let forever = animate(
88            clock,
89            Timing::new(AnimSpec {
90                repeat: u32::MAX,
91                ..AnimSpec::linear(1000)
92            }),
93            |sample| assert!(!sample.done),
94        );
95        let instant = Rc::new(RefCell::new(None));
96        let i = instant.clone();
97        let _instant = animate(
98            clock,
99            Timing::new(AnimSpec {
100                repeat: 1,
101                autoreverse: true,
102                ..AnimSpec::linear(0)
103            }),
104            move |sample| *i.borrow_mut() = Some(sample),
105        );
106        let cb = pending.borrow_mut().pop_front().unwrap();
107        cb(FrameStamp::new(1.0));
108        assert_eq!(samples.borrow()[0].done, fast);
109        assert_eq!(samples.borrow()[0].progress, 0.0); // autoreverse ends at its start
110        assert_eq!(finite.is_active(), !fast);
111        assert!(continuous.is_active() && forever.is_active());
112        let instant = instant.borrow().unwrap();
113        assert!(instant.done);
114        assert_eq!(instant.progress, 1.0); // zero-duration timing always applies its target
115    }
116}