petitcarnets 0.0.11

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! A stopwatch that counts up at an interval: Bubbles' `stopwatch`
//! package.
//!
//! Go reads the wall clock in `Update` and `View`; here the time comes
//! from the program's clock, in the messages, so a stopwatch in a
//! [`TestProgram`](crate::testing::TestProgram) follows its virtual
//! clock.
//!
//! ```
//! use petitcarnets::bubbles::stopwatch;
//!
//! let s = stopwatch::Model::new();
//! assert_eq!(s.view(), "0s");
//! assert!(!s.running());
//! ```

mod control;

use super::next_id;
use super::timer::go_duration;
use crate::{Cmd, Msg as TeaMsg};
use std::time::{Duration, SystemTime};

/// A stopwatch's messages.
///
/// ```
/// use petitcarnets as tea;
/// use std::time::{Duration, UNIX_EPOCH};
/// use tea::bubbles::stopwatch::{self, Msg};
///
/// let mut s = stopwatch::Model::new();
/// let id = s.id();
/// let start = Msg::StartStop {
///     id,
///     running: true,
///     at: UNIX_EPOCH,
/// };
/// assert!(s.update(&tea::Msg::App(start)).is_none());
/// let at = UNIX_EPOCH + Duration::from_secs(3);
/// assert!(
///     !s.update(&tea::Msg::App(Msg::Tick { id, at, tag: 0 }))
///         .is_none()
/// );
/// assert_eq!(s.view(), "3s");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Msg {
    /// Start or stop: Bubbles' `stopwatch.StartStopMsg`.
    StartStop {
        /// The stopwatch it is for.
        id: u64,
        /// Start or stop.
        running: bool,
        /// When, on the program's clock.
        at: SystemTime,
    },
    /// Back to zero: Bubbles' `stopwatch.ResetMsg`.
    Reset {
        /// The stopwatch it is for.
        id: u64,
        /// When, on the program's clock.
        at: SystemTime,
    },
    /// Time to count: Bubbles' `stopwatch.TickMsg`.
    Tick {
        /// The stopwatch it is for.
        id: u64,
        /// When, on the program's clock.
        at: SystemTime,
        /// Which tick, so an older one is ignored.
        tag: u64,
    },
}

/// A stopwatch: Bubbles' `stopwatch.Model`.
///
/// ```
/// use petitcarnets as tea;
/// use std::time::Duration;
/// use tea::bubbles::stopwatch;
/// use tea::testing::TestProgram;
/// # struct App(
/// #     stopwatch::Model,
/// #     fn(&stopwatch::Model) -> tea::Cmd<stopwatch::Msg>,
/// # );
/// #
/// # impl tea::Model for App {
/// #     type Msg = stopwatch::Msg;
/// #     fn init(&mut self) -> tea::Cmd<stopwatch::Msg> {
/// #         self.0.init()
/// #     }
/// #     fn update(&mut self, msg: tea::Msg<stopwatch::Msg>) -> tea::Cmd<stopwatch::Msg> {
/// #         match msg {
/// #             tea::Msg::KeyPress(_) => (self.1)(&self.0),
/// #             _ => self.0.update(&msg),
/// #         }
/// #     }
/// #     fn view(&self) -> tea::View {
/// #         tea::View::new(self.0.view())
/// #     }
/// # }
///
/// let mut test = TestProgram::new(App(stopwatch::Model::new(), stopwatch::Model::stop), 10, 1);
/// test.advance(Duration::from_millis(2500));
/// assert_eq!(test.model().0.view(), "2s");
/// assert!(test.model().0.running());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
    /// How often it ticks.
    pub interval: Duration,
    elapsed: Duration,
    start: Option<SystemTime>,
    id: u64,
    tag: u64,
    running: bool,
}

impl Default for Model {
    fn default() -> Self {
        Self::new()
    }
}

impl Model {
    /// A stopped stopwatch at zero, ticking every second once started:
    /// `stopwatch.New`.
    ///
    /// ```
    /// use petitcarnets::bubbles::stopwatch;
    /// use std::time::Duration;
    ///
    /// let s = stopwatch::Model::new();
    /// assert_eq!(s.interval, Duration::from_secs(1));
    /// assert_eq!(s.elapsed(), Duration::ZERO);
    /// assert!(!s.running());
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            interval: Duration::from_secs(1),
            elapsed: Duration::ZERO,
            start: None,
            id: next_id(),
            tag: 0,
            running: false,
        }
    }

    /// Ticking every `interval`: `stopwatch.WithInterval`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::{Duration, UNIX_EPOCH};
    /// use tea::bubbles::stopwatch::{self, Msg};
    ///
    /// let mut s = stopwatch::Model::new().with_interval(Duration::from_millis(100));
    /// let id = s.id();
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: true,
    ///     at: UNIX_EPOCH,
    /// }));
    /// let at = UNIX_EPOCH + Duration::from_millis(1250);
    /// let _ = s.update(&tea::Msg::App(Msg::Tick { id, at, tag: 0 }));
    /// assert_eq!(s.view(), "1.2s");
    /// ```
    #[must_use]
    pub const fn with_interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    /// The stopwatch's id.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::UNIX_EPOCH;
    /// use tea::bubbles::stopwatch::{self, Msg};
    ///
    /// let mut s = stopwatch::Model::new();
    /// let other = stopwatch::Model::new();
    /// assert_ne!(s.id(), other.id());
    /// let id = other.id();
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: true,
    ///     at: UNIX_EPOCH,
    /// }));
    /// assert!(!s.running(), "not its message");
    /// ```
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id
    }

    /// Starts it: Go's `Init`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::Duration;
    /// use tea::bubbles::stopwatch;
    /// use tea::testing::TestProgram;
    /// # struct App(
    /// #     stopwatch::Model,
    /// #     fn(&stopwatch::Model) -> tea::Cmd<stopwatch::Msg>,
    /// # );
    /// #
    /// # impl tea::Model for App {
    /// #     type Msg = stopwatch::Msg;
    /// #     fn init(&mut self) -> tea::Cmd<stopwatch::Msg> {
    /// #         self.0.init()
    /// #     }
    /// #     fn update(&mut self, msg: tea::Msg<stopwatch::Msg>) -> tea::Cmd<stopwatch::Msg> {
    /// #         match msg {
    /// #             tea::Msg::KeyPress(_) => (self.1)(&self.0),
    /// #             _ => self.0.update(&msg),
    /// #         }
    /// #     }
    /// #     fn view(&self) -> tea::View {
    /// #         tea::View::new(self.0.view())
    /// #     }
    /// # }
    ///
    /// // The app starts the stopwatch, then calls `stop` on a key.
    /// let app = App(stopwatch::Model::new(), stopwatch::Model::stop);
    /// let mut test = TestProgram::new(app, 10, 1);
    /// test.advance(Duration::from_secs(3));
    /// assert_eq!(test.model().0.view(), "3s");
    /// ```
    pub fn init(&self) -> Cmd<Msg> {
        self.start()
    }

    /// Whether it is running.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::Duration;
    /// use tea::bubbles::stopwatch;
    /// use tea::testing::TestProgram;
    /// # struct App(
    /// #     stopwatch::Model,
    /// #     fn(&stopwatch::Model) -> tea::Cmd<stopwatch::Msg>,
    /// # );
    /// #
    /// # impl tea::Model for App {
    /// #     type Msg = stopwatch::Msg;
    /// #     fn init(&mut self) -> tea::Cmd<stopwatch::Msg> {
    /// #         self.0.init()
    /// #     }
    /// #     fn update(&mut self, msg: tea::Msg<stopwatch::Msg>) -> tea::Cmd<stopwatch::Msg> {
    /// #         match msg {
    /// #             tea::Msg::KeyPress(_) => (self.1)(&self.0),
    /// #             _ => self.0.update(&msg),
    /// #         }
    /// #     }
    /// #     fn view(&self) -> tea::View {
    /// #         tea::View::new(self.0.view())
    /// #     }
    /// # }
    ///
    /// // The app starts the stopwatch, then calls `stop` on a key.
    /// let app = App(stopwatch::Model::new(), stopwatch::Model::stop);
    /// let mut test = TestProgram::new(app, 10, 1);
    /// assert!(test.model().0.running());
    /// test.press(tea::Key::char('s'));
    /// assert!(!test.model().0.running());
    /// ```
    #[must_use]
    pub const fn running(&self) -> bool {
        self.running
    }

    /// Starts, stops, resets and counts on its own messages.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::{Duration, UNIX_EPOCH};
    /// use tea::bubbles::stopwatch::{self, Msg};
    ///
    /// let mut s = stopwatch::Model::new();
    /// let id = s.id();
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: true,
    ///     at: UNIX_EPOCH,
    /// }));
    /// let at = UNIX_EPOCH + Duration::from_secs(5);
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: false,
    ///     at,
    /// }));
    /// assert_eq!(s.elapsed(), Duration::from_secs(5));
    /// let _ = s.update(&tea::Msg::App(Msg::Reset { id, at }));
    /// assert_eq!(s.elapsed(), Duration::ZERO);
    /// ```
    pub fn update(&mut self, msg: &TeaMsg<Msg>) -> Cmd<Msg> {
        match msg {
            TeaMsg::App(Msg::StartStop { id, running, at }) if *id == self.id => {
                self.start_stop(*running, *at);
            }
            TeaMsg::App(Msg::Reset { id, at }) if *id == self.id => {
                self.elapsed = Duration::ZERO;
                self.start = Some(*at);
            }
            TeaMsg::App(Msg::Tick { id, at, tag }) if self.running && *id == self.id => {
                return self.on_tick(*at, *tag);
            }
            _ => {}
        }
        Cmd::none()
    }

    /// Starts or stops at `at`.
    fn start_stop(&mut self, running: bool, at: SystemTime) {
        match (self.running, running) {
            (false, true) => self.start = Some(at),
            (true, false) => self.count(at),
            _ => {}
        }
        self.running = running;
    }

    /// Its tick `tag` at `at`: counts, and asks for the next.
    fn on_tick(&mut self, at: SystemTime, tag: u64) -> Cmd<Msg> {
        if tag > 0 && tag != self.tag {
            return Cmd::none();
        }
        self.count(at);
        self.tag += 1;
        tick(self.id, self.tag, self.interval)
    }

    /// Adds the time since the last count.
    fn count(&mut self, at: SystemTime) {
        let since = self
            .start
            .and_then(|s| at.duration_since(s).ok())
            .unwrap_or_default();
        self.elapsed += since;
        self.start = Some(at);
    }

    /// The time counted, up to the last message.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::{Duration, UNIX_EPOCH};
    /// use tea::bubbles::stopwatch::{self, Msg};
    ///
    /// let mut s = stopwatch::Model::new();
    /// let id = s.id();
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: true,
    ///     at: UNIX_EPOCH,
    /// }));
    /// let at = UNIX_EPOCH + Duration::from_millis(1750);
    /// let _ = s.update(&tea::Msg::App(Msg::Tick { id, at, tag: 0 }));
    /// assert_eq!(s.elapsed(), Duration::from_millis(1750));
    /// assert_eq!(s.view(), "1s", "the view is cut to the interval");
    /// ```
    #[must_use]
    pub const fn elapsed(&self) -> Duration {
        self.elapsed
    }

    /// The time counted, cut to the interval, as Go writes a duration.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::{Duration, UNIX_EPOCH};
    /// use tea::bubbles::stopwatch::{self, Msg};
    ///
    /// let mut s = stopwatch::Model::new();
    /// assert_eq!(s.view(), "0s");
    /// let id = s.id();
    /// let _ = s.update(&tea::Msg::App(Msg::StartStop {
    ///     id,
    ///     running: true,
    ///     at: UNIX_EPOCH,
    /// }));
    /// let at = UNIX_EPOCH + Duration::from_secs(61);
    /// let _ = s.update(&tea::Msg::App(Msg::Tick { id, at, tag: 0 }));
    /// assert_eq!(s.view(), "1m1s");
    /// ```
    #[must_use]
    pub fn view(&self) -> String {
        let step = if self.interval.is_zero() {
            Duration::from_secs(1)
        } else {
            self.interval
        };
        let steps = self.elapsed.as_nanos() / step.as_nanos();
        let cut = step.checked_mul(u32::try_from(steps).unwrap_or(u32::MAX));
        go_duration(cut.unwrap_or(self.elapsed))
    }
}

/// The tick `tag` for stopwatch `id`, after `interval`.
fn tick(id: u64, tag: u64, interval: Duration) -> Cmd<Msg> {
    crate::tick(interval, move |at| Msg::Tick { id, at, tag })
}

#[cfg(test)]
mod tests;