Skip to main content

euv_ui/hook/previous/
impl.rs

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