Skip to main content

euv_ui/hook/previous/
impl.rs

1use super::*;
2
3impl<T: Clone + PartialEq + 'static> Previous<T> {
4    /// Creates a new `Previous` with no recorded value.
5    /// The `previous` signal starts at `None`.
6    pub fn new() -> Self {
7        Self {
8            previous: Signal::create(None),
9        }
10    }
11
12    /// Records `current` as the new previous value. The
13    /// next call to `get_previous_snapshot()` will return
14    /// `Some(current)`.
15    ///
16    /// This is typically called at the top of a render
17    /// closure so the signal stores the value just seen.
18    ///
19    /// # Arguments
20    ///
21    /// - `T: Clone + PartialEq + 'static` - A generic type parameter.
22    pub fn record(&self, current: T) {
23        self.get_previous().set(Some(current));
24    }
25
26    /// Returns a snapshot of the previously recorded
27    /// value, or `None` if no value has been recorded yet.
28    ///
29    /// # Returns
30    ///
31    /// - `Option<T>` - The previous captured value, or `None`.
32    pub fn get_previous_snapshot(&self) -> Option<T> {
33        self.get_previous().get()
34    }
35
36    /// Clears the recorded previous value, returning the
37    /// tracker to the `None` state.
38    pub fn clear(&self) {
39        self.get_previous().set(None);
40    }
41}
42
43impl<T: Clone + PartialEq + Debug + 'static> Display for Previous<T> {
44    /// Formats the [`Previous`] via the supplied formatter.
45    ///
46    /// # Arguments
47    ///
48    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
49    ///
50    /// # Returns
51    ///
52    /// - `FmtResult` - Result of the formatting operation.
53    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
54        match self.get_previous().get() {
55            Some(value) => write!(formatter, "Previous(Some({value:?}))"),
56            None => write!(formatter, "Previous(None)"),
57        }
58    }
59}
60
61impl<T: Clone + PartialEq + 'static> Default for Previous<T> {
62    /// Constructs a default [`Previous`] value.
63    fn default() -> Self {
64        Self::new()
65    }
66}