#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum MotionPreference {
#[default]
Full,
Reduced,
Off,
}
impl MotionPreference {
pub const ALL: [Self; 3] = [Self::Full, Self::Reduced, Self::Off];
pub const fn label(self) -> &'static str {
match self {
Self::Full => "Full",
Self::Reduced => "Reduced",
Self::Off => "Off",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MotionPolicy {
pub preference: MotionPreference,
pub time_scale: f32,
}
impl MotionPolicy {
pub const MIN_TIME_SCALE: f32 = 0.01;
pub const FULL: Self = Self::new(MotionPreference::Full);
pub const fn new(preference: MotionPreference) -> Self {
Self {
preference,
time_scale: 1.0,
}
}
pub const fn with_time_scale(mut self, time_scale: f32) -> Self {
self.time_scale = time_scale;
self
}
pub fn allows_motion(self) -> bool {
self.preference != MotionPreference::Off
}
pub fn allows_movement(self) -> bool {
self.preference == MotionPreference::Full
}
pub fn time_scale(self) -> f32 {
if self.time_scale.is_finite() {
self.time_scale.max(Self::MIN_TIME_SCALE)
} else {
1.0
}
}
pub fn duration(self, nominal: f64) -> f64 {
if self.allows_motion() {
nominal.max(0.0) / f64::from(self.time_scale())
} else {
0.0
}
}
pub fn movement_duration(self, nominal: f64) -> f64 {
if self.allows_movement() {
self.duration(nominal)
} else {
0.0
}
}
pub fn scale_delta(self, delta: f64) -> f64 {
delta * f64::from(self.time_scale())
}
pub fn entrance_offset(self, progress: f32) -> f32 {
if self.allows_movement() {
1.0 - progress
} else {
0.0
}
}
}
impl Default for MotionPolicy {
fn default() -> Self {
Self::FULL
}
}
#[cfg(test)]
mod tests {
use super::{MotionPolicy, MotionPreference};
#[test]
fn full_motion_keeps_nominal_durations() {
let policy = MotionPolicy::FULL;
assert_eq!(policy.duration(0.14), 0.14);
assert_eq!(policy.movement_duration(0.14), 0.14);
assert_eq!(policy.entrance_offset(0.25), 0.75);
}
#[test]
fn time_scale_stretches_durations_and_slows_deltas() {
let policy = MotionPolicy::FULL.with_time_scale(0.25);
assert_eq!(policy.duration(0.1), 0.4);
assert_eq!(policy.scale_delta(0.1), 0.025);
assert_eq!(
MotionPolicy::FULL.with_time_scale(0.0).time_scale(),
MotionPolicy::MIN_TIME_SCALE
);
assert_eq!(
MotionPolicy::FULL.with_time_scale(f32::NAN).time_scale(),
1.0
);
}
#[test]
fn reduced_motion_keeps_fades_but_drops_movement() {
let policy = MotionPolicy::new(MotionPreference::Reduced);
assert!(policy.allows_motion());
assert!(!policy.allows_movement());
assert_eq!(policy.duration(0.14), 0.14);
assert_eq!(policy.movement_duration(0.14), 0.0);
assert_eq!(policy.entrance_offset(0.25), 0.0);
}
#[test]
fn motion_off_finishes_every_transition_immediately() {
let policy = MotionPolicy::new(MotionPreference::Off);
assert!(!policy.allows_motion());
assert_eq!(policy.duration(0.34), 0.0);
assert_eq!(policy.movement_duration(0.34), 0.0);
}
}