Skip to main content

mln_style/property/
transition.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use crate::collections::VecSet;
5#[cfg(doc)]
6use crate::constants::DEFAULT_STYLE_TRANSITION_EASE;
7use crate::conversion::{Converter, Convertible, Error};
8use crate::expression::GlobalStateMap;
9use crate::feature::{Value, ValueObject};
10use crate::time::Instant;
11
12#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
13pub struct TransitionOptions {
14    pub duration: Option<Duration>,
15    pub delay: Option<Duration>,
16    /// The control points (x1, y1, x2, y2) of the cubic Bézier that eases
17    /// the transition, with x1 and x2 between 0 and 1.
18    /// [`DEFAULT_STYLE_TRANSITION_EASE`] when no transition sets one.
19    ///
20    /// A style can't set it: the style spec has no such key.
21    pub easing: Option<[f64; 4]>,
22    pub enable_placement_transitions: bool,
23}
24
25impl Default for TransitionOptions {
26    fn default() -> Self {
27        TransitionOptions::new(None, None, true)
28    }
29}
30
31impl TransitionOptions {
32    #[must_use]
33    pub fn new(duration: Option<Duration>, delay: Option<Duration>, enable_placement_transitions: bool) -> Self {
34        TransitionOptions { duration, delay, easing: None, enable_placement_transitions }
35    }
36
37    #[must_use]
38    pub(crate) fn with_duration(duration: Duration) -> Self {
39        TransitionOptions::new(Some(duration), None, true)
40    }
41
42    #[must_use]
43    pub(crate) fn is_defined(&self) -> bool {
44        self.duration.is_some() || self.delay.is_some()
45    }
46
47    #[must_use]
48    pub(crate) fn serialize(&self) -> Value {
49        PropertyTransition { duration: self.duration, delay: self.delay }.serialize()
50    }
51}
52
53/// A property's own transition, as a layer's `*-transition` sets it. The
54/// style's default transition fills in what it leaves unset, and holds what
55/// only the host sets.
56#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
57pub(crate) struct PropertyTransition {
58    pub(crate) duration: Option<Duration>,
59    pub(crate) delay: Option<Duration>,
60}
61
62impl PropertyTransition {
63    /// This transition, with the style's `defaults` for what it leaves unset.
64    #[must_use]
65    pub(crate) fn merged(&self, defaults: &TransitionOptions) -> TransitionOptions {
66        TransitionOptions {
67            duration: self.duration.or(defaults.duration),
68            delay: self.delay.or(defaults.delay),
69            ..*defaults
70        }
71    }
72
73    #[must_use]
74    pub(crate) fn is_defined(&self) -> bool {
75        self.duration.is_some() || self.delay.is_some()
76    }
77
78    #[must_use]
79    pub(crate) fn serialize(&self) -> Value {
80        let mut result = ValueObject::new();
81        // Whole milliseconds, as integers.
82        let millis = |duration: Duration| Value::Int(i64::try_from(duration.as_millis()).unwrap_or(i64::MAX));
83        if let Some(duration) = self.duration {
84            result.insert("duration".to_owned(), millis(duration));
85        }
86        if let Some(delay) = self.delay {
87            result.insert("delay".to_owned(), millis(delay));
88        }
89        Value::Object(result)
90    }
91}
92
93/// A change of the style's global state, across which the values that read it
94/// transition from what they showed before.
95#[derive(Clone, Debug)]
96pub struct GlobalStateChange {
97    /// The state before the change, which transitions already running keep reading.
98    pub prior_state: Arc<GlobalStateMap>,
99    /// The keys whose values differ between the prior and the current state.
100    pub changed_keys: Arc<VecSet<String>>,
101    /// Whether the global state is all that changed, so only the values that
102    /// read a changed key start a new transition.
103    pub state_only: bool,
104}
105
106#[derive(Clone, Debug, Default)]
107pub struct TransitionParameters {
108    /// When the transitions start; `None` starts them ended.
109    pub now: Option<Instant>,
110    pub transition: TransitionOptions,
111    /// Set when the global state changed since the last transition.
112    pub global_state_change: Option<GlobalStateChange>,
113}
114
115impl TransitionParameters {
116    /// Parameters without a global-state change.
117    #[must_use]
118    pub fn new(now: Option<Instant>, transition: TransitionOptions) -> Self {
119        TransitionParameters { now, transition, global_state_change: None }
120    }
121}
122
123/// `number` milliseconds, truncated to whole milliseconds; a negative
124/// number, below the style spec's minimum of 0, gives zero, as does NaN.
125fn whole_milliseconds(number: f32) -> Duration {
126    Duration::from_millis(number as u64)
127}
128
129impl Converter for TransitionOptions {
130    fn convert(value: &Convertible<'_>, error: &mut Error) -> Option<TransitionOptions> {
131        let PropertyTransition { duration, delay } = PropertyTransition::convert(value, error)?;
132        Some(TransitionOptions::new(duration, delay, true))
133    }
134}
135
136impl Converter for PropertyTransition {
137    fn convert(value: &Convertible<'_>, error: &mut Error) -> Option<PropertyTransition> {
138        if !value.is_object() {
139            error.message = "transition must be an object".to_owned();
140            return None;
141        }
142
143        let mut result = PropertyTransition::default();
144
145        if let Some(duration) = value.object_member("duration") {
146            let Some(number) = duration.to_number() else {
147                error.message = "duration must be a number".to_owned();
148                return None;
149            };
150            result.duration = Some(whole_milliseconds(number));
151        }
152
153        if let Some(delay) = value.object_member("delay") {
154            let Some(number) = delay.to_number() else {
155                error.message = "delay must be a number".to_owned();
156                return None;
157            };
158            result.delay = Some(whole_milliseconds(number));
159        }
160
161        Some(result)
162    }
163}