Skip to main content

waft_material/
time.rs

1//! Flutter counterpart: material_ui's `time.dart`.
2//!
3//! [`TimeOfDayFormat`] and [`HourFormat`] keep Dart's names: they are ICU patterns, where
4//! `H` and `h` are different hours.
5
6use std::cmp::Ordering;
7use std::fmt;
8
9use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, DateTime, Handle, Ref};
10use waft_services::RestorationData;
11use waft_widgets::{
12    BuildContext, MediaQuery, RestorableProperty, RestorablePropertyData, RestorableValue,
13    RestorableValueData, debug_check_has_media_query,
14};
15
16use crate::debug::debug_check_has_material_localizations;
17use crate::material_localizations::MaterialLocalizations;
18
19/// Whether the [`TimeOfDay`] is before or after noon.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum DayPeriod {
22    /// Ante meridiem (before noon).
23    Am,
24
25    /// Post meridiem (after noon).
26    Pm,
27}
28
29/// A value representing a time during the day, independent of the date that
30/// day might fall on or the time zone.
31///
32/// The time is represented by [`hour`](Self::hour) and [`minute`](Self::minute) pair. Once
33/// created, both values cannot be changed.
34///
35/// You can create TimeOfDay using the constructor which requires both hour and
36/// minute or using [`DateTime`] object.
37/// Hours are specified between 0 and 23, as in a 24-hour clock.
38///
39/// ```
40/// # use waft_foundation::{AppCell, DateTime};
41/// # use waft_material::TimeOfDay;
42/// # let cell = AppCell::new();
43/// # let app = cell.borrow();
44/// let release_time = TimeOfDay::new(15, 0); // 3:00pm
45/// let booking = DateTime::new_with_time(&app, 2018, 10, 20, 16, 30, 4, 0, 0);
46/// let room_booked = TimeOfDay::from_date_time(&app, &booking); // 4:30pm
47/// ```
48///
49/// See also:
50///
51///  * `showTimePicker`, which returns this type.
52///  * [`MaterialLocalizations`], which provides methods for formatting values of
53///    this type according to the chosen `Locale`.
54///  * [`DateTime`], which represents date and time, and is subject to eras and
55///    time zones.
56#[derive(Clone, Copy, PartialEq, Eq, Hash)]
57pub struct TimeOfDay {
58    /// The selected hour, in 24 hour time from 0..23.
59    pub hour: i32,
60
61    /// The selected minute.
62    pub minute: i32,
63}
64
65impl TimeOfDay {
66    /// Creates a time of day.
67    ///
68    /// The `hour` argument must be between 0 and 23, inclusive. The `minute`
69    /// argument must be between 0 and 59, inclusive.
70    pub const fn new(hour: i32, minute: i32) -> TimeOfDay {
71        TimeOfDay { hour, minute }
72    }
73
74    /// Creates a time of day based on the current time, in the local time zone.
75    pub fn now(app: &App) -> TimeOfDay {
76        TimeOfDay::from_date_time(app, &DateTime::now())
77    }
78
79    /// Creates a time of day based on the given time.
80    ///
81    /// The [`hour`](Self::hour) is set to the time's hour and the [`minute`](Self::minute) is
82    /// set to the time's minute in the timezone of the given [`DateTime`].
83    pub fn from_date_time(app: &App, time: &DateTime) -> TimeOfDay {
84        TimeOfDay {
85            hour: time.hour(app),
86            minute: time.minute(app),
87        }
88    }
89
90    /// The number of hours in one day, i.e. 24.
91    pub const HOURS_PER_DAY: i32 = 24;
92
93    /// The number of hours in one day period (see also [`DayPeriod`]), i.e. 12.
94    pub const HOURS_PER_PERIOD: i32 = 12;
95
96    /// The number of minutes in one hour, i.e. 60.
97    pub const MINUTES_PER_HOUR: i32 = 60;
98
99    /// Returns a new TimeOfDay with the hour and/or minute replaced.
100    pub fn replacing(&self, hour: Option<i32>, minute: Option<i32>) -> TimeOfDay {
101        debug_assert!(hour.is_none_or(|hour| (0..Self::HOURS_PER_DAY).contains(&hour)));
102        debug_assert!(minute.is_none_or(|minute| (0..Self::MINUTES_PER_HOUR).contains(&minute)));
103        TimeOfDay::new(hour.unwrap_or(self.hour), minute.unwrap_or(self.minute))
104    }
105
106    /// Whether this time of day is before or after noon.
107    pub fn period(&self) -> DayPeriod {
108        if self.hour < Self::HOURS_PER_PERIOD {
109            DayPeriod::Am
110        } else {
111            DayPeriod::Pm
112        }
113    }
114
115    /// Which hour of the current period (e.g., am or pm) this time is.
116    ///
117    /// For 12AM (midnight) and 12PM (noon) this returns 12.
118    pub fn hour_of_period(&self) -> i32 {
119        if self.hour == 0 || self.hour == 12 {
120            12
121        } else {
122            self.hour - self.period_offset()
123        }
124    }
125
126    /// The hour at which the current period starts.
127    pub fn period_offset(&self) -> i32 {
128        if self.period() == DayPeriod::Am {
129            0
130        } else {
131            Self::HOURS_PER_PERIOD
132        }
133    }
134
135    /// Returns the localized string representation of this time of day.
136    ///
137    /// This is a shortcut for [`MaterialLocalizations::format_time_of_day`].
138    pub fn format(&self, app: &mut App, context: BuildContext) -> String {
139        debug_assert!(debug_check_has_media_query(app, context));
140        debug_assert!(debug_check_has_material_localizations(app, context));
141        let localizations = <dyn MaterialLocalizations>::of(app, context);
142        localizations
143            .format_time_of_day(self, MediaQuery::always_use_24_hour_format_of(app, context))
144    }
145
146    /// Whether this [`TimeOfDay`] occurs earlier than `other`.
147    ///
148    /// Does not account for day or sub-minute differences. This means
149    /// that "00:00" of the next day is still before "23:00" of this day.
150    pub fn is_before(&self, other: &TimeOfDay) -> bool {
151        self.compare_to(other) == Ordering::Less
152    }
153
154    /// Whether this [`TimeOfDay`] occurs later than `other`.
155    ///
156    /// Does not account for day or sub-minute differences. This means
157    /// that "00:00" of the next day is still before "23:00" of this day.
158    pub fn is_after(&self, other: &TimeOfDay) -> bool {
159        self.compare_to(other) == Ordering::Greater
160    }
161
162    /// Whether this [`TimeOfDay`] occurs at the same time as `other`.
163    ///
164    /// Does not account for day or sub-minute differences. This means
165    /// that "00:00" of the next day is still before "23:00" of this day.
166    pub fn is_at_same_time_as(&self, other: &TimeOfDay) -> bool {
167        self.compare_to(other) == Ordering::Equal
168    }
169
170    /// Compares this [`TimeOfDay`] object to `other` independent of date.
171    ///
172    /// Does not account for day or sub-minute differences. This means
173    /// that "00:00" of the next day is still before "23:00" of this day.
174    ///
175    /// A [`compare_to`](Self::compare_to) function returns:
176    ///  * [`Ordering::Less`] if this TimeOfDay [`is_before`](Self::is_before) `other`.
177    ///  * [`Ordering::Equal`] if this DateTime [`is_at_same_time_as`](Self::is_at_same_time_as)
178    ///    `other`, and
179    ///  * [`Ordering::Greater`] otherwise (when this TimeOfDay [`is_after`](Self::is_after)
180    ///    `other`).
181    pub fn compare_to(&self, other: &TimeOfDay) -> Ordering {
182        let hour_comparison = self.hour.cmp(&other.hour);
183        if hour_comparison == Ordering::Equal {
184            self.minute.cmp(&other.minute)
185        } else {
186            hour_comparison
187        }
188    }
189}
190
191/// Dart's `implements Comparable<TimeOfDay>`: the order of [`TimeOfDay::compare_to`].
192impl Ord for TimeOfDay {
193    fn cmp(&self, other: &TimeOfDay) -> Ordering {
194        self.compare_to(other)
195    }
196}
197
198impl PartialOrd for TimeOfDay {
199    fn partial_cmp(&self, other: &TimeOfDay) -> Option<Ordering> {
200        Some(self.cmp(other))
201    }
202}
203
204impl fmt::Debug for TimeOfDay {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        fn add_leading_zero_if_needed(value: i32) -> String {
207            if value < 10 {
208                return format!("0{value}");
209            }
210            value.to_string()
211        }
212
213        let hour_label = add_leading_zero_if_needed(self.hour);
214        let minute_label = add_leading_zero_if_needed(self.minute);
215
216        write!(f, "TimeOfDay({hour_label}:{minute_label})")
217    }
218}
219
220/// A [`RestorableValue`] that knows how to save and restore [`TimeOfDay`].
221///
222/// The current value of this property is stored in the restoration data. During state
223/// restoration the property is restored to the value it had when the restoration data it is
224/// getting restored from was collected.
225///
226/// If no restoration data is available, the value is initialized to the `default_value` given
227/// in the constructor.
228pub struct RestorableTimeOfDay {
229    change_notifier: ChangeNotifierData,
230    property: RestorablePropertyData,
231    value: RestorableValueData<TimeOfDay>,
232    default_value: TimeOfDay,
233}
234
235impl RestorableTimeOfDay {
236    /// Creates a [`RestorableTimeOfDay`].
237    ///
238    /// If no restoration data is available to restore the value in this property from, the
239    /// property will be initialized with the provided `default_value`.
240    pub fn new(app: &mut App, default_value: TimeOfDay) -> Ref<RestorableTimeOfDay> {
241        app.create(RestorableTimeOfDay {
242            change_notifier: ChangeNotifierData::new(),
243            property: RestorablePropertyData::new(),
244            value: RestorableValueData::new(),
245            default_value,
246        })
247    }
248}
249
250impl ChangeNotifier for RestorableTimeOfDay {
251    fn change_notifier_data(&self) -> &ChangeNotifierData {
252        &self.change_notifier
253    }
254
255    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
256        &mut self.change_notifier
257    }
258}
259
260impl RestorableProperty for RestorableTimeOfDay {
261    type Value = TimeOfDay;
262    waft_widgets::restorable_property_accessors!();
263
264    fn create_default_value(self: Handle<Self>, app: &mut App) -> TimeOfDay {
265        app.get(self).default_value
266    }
267
268    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> TimeOfDay {
269        let _ = app;
270        let time_data = data
271            .as_list()
272            .expect("the restoration data of a TimeOfDay property is a list");
273        let int_at = |index: usize| {
274            let value = time_data[index]
275                .as_int()
276                .expect("the restoration data of a TimeOfDay property holds ints");
277            i32::try_from(value).expect("an hour or a minute")
278        };
279        TimeOfDay::new(int_at(1), int_at(0))
280    }
281
282    fn init_with_value(self: Handle<Self>, app: &mut App, value: TimeOfDay) {
283        RestorableValue::init_with_value(self, app, value);
284    }
285
286    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
287        let value = RestorableValue::value(self, app);
288        RestorationData::List(vec![
289            RestorationData::Int(i64::from(value.minute)),
290            RestorationData::Int(i64::from(value.hour)),
291        ])
292    }
293}
294
295impl RestorableValue for RestorableTimeOfDay {
296    waft_widgets::restorable_value_accessors!();
297
298    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<TimeOfDay>) {
299        let _ = old_value;
300        self.notify_listeners(app);
301    }
302}
303
304/// Determines how the time picker invoked using `showTimePicker` formats and
305/// lays out the time controls.
306///
307/// The time picker provides layout configurations optimized for each of the
308/// enum values.
309#[allow(
310    non_camel_case_types,
311    reason = "Dart's names are ICU patterns, where the case of a letter is its meaning"
312)]
313#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
314pub enum TimeOfDayFormat {
315    /// Corresponds to the ICU 'HH:mm' pattern.
316    ///
317    /// This format uses 24-hour two-digit zero-padded hours. Controls are always
318    /// laid out horizontally. Hours are separated from minutes by one colon
319    /// character.
320    HH_colon_mm,
321
322    /// Corresponds to the ICU 'HH.mm' pattern.
323    ///
324    /// This format uses 24-hour two-digit zero-padded hours. Controls are always
325    /// laid out horizontally. Hours are separated from minutes by one dot
326    /// character.
327    HH_dot_mm,
328
329    /// Corresponds to the ICU "HH 'h' mm" pattern used in Canadian French.
330    ///
331    /// This format uses 24-hour two-digit zero-padded hours. Controls are always
332    /// laid out horizontally. Hours are separated from minutes by letter 'h'.
333    FrenchCanadian,
334
335    /// Corresponds to the ICU 'H:mm' pattern.
336    ///
337    /// This format uses 24-hour non-padded variable-length hours. Controls are
338    /// always laid out horizontally. Hours are separated from minutes by one
339    /// colon character.
340    H_colon_mm,
341
342    /// Corresponds to the ICU 'h:mm a' pattern.
343    ///
344    /// This format uses 12-hour non-padded variable-length hours with a day
345    /// period. Controls are laid out horizontally in portrait mode. In landscape
346    /// mode, the day period appears vertically after (consistent with the ambient
347    /// `TextDirection`) hour-minute indicator. Hours are separated from minutes
348    /// by one colon character.
349    h_colon_mm_space_a,
350
351    /// Corresponds to the ICU 'a h:mm' pattern.
352    ///
353    /// This format uses 12-hour non-padded variable-length hours with a day
354    /// period. Controls are laid out horizontally in portrait mode. In landscape
355    /// mode, the day period appears vertically before (consistent with the
356    /// ambient `TextDirection`) hour-minute indicator. Hours are separated from
357    /// minutes by one colon character.
358    a_space_h_colon_mm,
359}
360
361/// Describes how hours are formatted.
362#[allow(
363    non_camel_case_types,
364    clippy::upper_case_acronyms,
365    reason = "Dart's names are ICU patterns, where `H` and `h` are different hours"
366)]
367#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
368pub enum HourFormat {
369    /// Zero-padded two-digit 24-hour format ranging from "00" to "23".
370    HH,
371
372    /// Non-padded variable-length 24-hour format ranging from "0" to "23".
373    H,
374
375    /// Non-padded variable-length hour in day period format ranging from "1" to
376    /// "12".
377    h,
378}
379
380/// The [`HourFormat`] used for the given [`TimeOfDayFormat`].
381pub fn hour_format(of: TimeOfDayFormat) -> HourFormat {
382    match of {
383        TimeOfDayFormat::h_colon_mm_space_a | TimeOfDayFormat::a_space_h_colon_mm => HourFormat::h,
384        TimeOfDayFormat::H_colon_mm => HourFormat::H,
385        TimeOfDayFormat::HH_dot_mm
386        | TimeOfDayFormat::HH_colon_mm
387        | TimeOfDayFormat::FrenchCanadian => HourFormat::HH,
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use std::cell::RefCell;
394    use std::rc::Rc;
395
396    use waft_foundation::{AppCell, Listenable, Listener};
397    use waft_services::{RestorationBucket, RestorationManager, RestorationMap};
398    use waft_widgets::testing::{WidgetTester, test_widgets};
399    use waft_widgets::{
400        Builder, GlobalKey, IntoWidget, KeyRef, MediaQueryData, RestorationMixin,
401        RestorationMixinData, RootRestorationScope, SizedBox, State, StateData, StatefulWidget,
402        WidgetRef,
403    };
404
405    use super::*;
406    use crate::material_localizations::tests::us_english;
407
408    // time_test.dart 'hourFormat'.
409    #[test]
410    fn hour_format_names_the_hours_of_each_time_of_day_format() {
411        for format in [
412            TimeOfDayFormat::h_colon_mm_space_a,
413            TimeOfDayFormat::a_space_h_colon_mm,
414        ] {
415            assert_eq!(hour_format(format), HourFormat::h, "for {format:?}");
416        }
417
418        assert_eq!(hour_format(TimeOfDayFormat::H_colon_mm), HourFormat::H);
419
420        for format in [
421            TimeOfDayFormat::HH_dot_mm,
422            TimeOfDayFormat::HH_colon_mm,
423            TimeOfDayFormat::FrenchCanadian,
424        ] {
425            assert_eq!(hour_format(format), HourFormat::HH, "for {format:?}");
426        }
427    }
428
429    // time_test.dart 'TimeOfDay.format respects alwaysUse24HourFormat option'.
430    #[test]
431    fn format_respects_always_use_24_hour_format() {
432        let pump_test = |always_use_24_hour_format: bool| {
433            let mut formatted = String::new();
434            test_widgets(|tester| {
435                let formatted_value = Rc::new(RefCell::new(String::new()));
436                let probe = Builder::new({
437                    let formatted_value = Rc::clone(&formatted_value);
438                    move |app, context| {
439                        *formatted_value.borrow_mut() = TimeOfDay::new(7, 0).format(app, context);
440                        SizedBox::shrink().into_widget()
441                    }
442                });
443                tester.pump_widget(us_english(
444                    MediaQuery::new(
445                        MediaQueryData::new().always_use_24_hour_format(always_use_24_hour_format),
446                        probe,
447                    )
448                    .into_widget(),
449                ));
450                formatted = formatted_value.take();
451            });
452            formatted
453        };
454
455        assert_eq!(pump_test(false), "7:00 AM");
456        assert_eq!(pump_test(true), "07:00");
457    }
458
459    // time_test.dart 'hourOfPeriod returns correct value'.
460    #[test]
461    fn hour_of_period_counts_from_twelve() {
462        let expected = [
463            12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
464        ];
465        for (hour, hour_of_period) in (0..24).zip(expected) {
466            assert_eq!(
467                TimeOfDay::new(hour, 0).hour_of_period(),
468                hour_of_period,
469                "hour {hour}"
470            );
471        }
472    }
473
474    // time_test.dart 'correctly compares to other TimeOfDays'.
475    #[test]
476    fn a_time_of_day_compares_by_hour_then_minute() {
477        let time = TimeOfDay::new;
478
479        assert_eq!(time(0, 0).compare_to(&time(1, 0)), Ordering::Less);
480        assert_eq!(time(20, 0).compare_to(&time(20, 1)), Ordering::Less);
481        assert_eq!(time(0, 0).compare_to(&time(0, 0)), Ordering::Equal);
482        assert_eq!(time(1, 0).compare_to(&time(0, 0)), Ordering::Greater);
483        assert_eq!(time(20, 1).compare_to(&time(20, 0)), Ordering::Greater);
484
485        assert!(time(0, 0).is_before(&time(1, 0)));
486        assert!(time(0, 0).is_before(&time(23, 0)));
487        assert!(time(0, 0).is_before(&time(0, 10)));
488        assert!(!time(0, 0).is_before(&time(0, 0)));
489        assert!(!time(1, 0).is_before(&time(0, 0)));
490        assert!(!time(23, 0).is_before(&time(0, 0)));
491        assert!(!time(0, 10).is_before(&time(0, 0)));
492
493        assert!(!time(0, 0).is_after(&time(1, 0)));
494        assert!(!time(0, 0).is_after(&time(23, 0)));
495        assert!(!time(0, 0).is_after(&time(0, 10)));
496        assert!(!time(0, 0).is_after(&time(0, 0)));
497        assert!(time(1, 0).is_after(&time(0, 0)));
498        assert!(time(23, 0).is_after(&time(0, 0)));
499        assert!(time(0, 10).is_after(&time(0, 0)));
500
501        assert!(!time(0, 0).is_at_same_time_as(&time(1, 0)));
502        assert!(!time(0, 0).is_at_same_time_as(&time(0, 10)));
503        assert!(time(0, 0).is_at_same_time_as(&time(0, 0)));
504        assert!(!time(1, 0).is_at_same_time_as(&time(0, 0)));
505        assert!(!time(0, 10).is_at_same_time_as(&time(0, 0)));
506    }
507
508    #[test]
509    fn a_time_of_day_sorts_as_it_compares() {
510        let mut times = vec![
511            TimeOfDay::new(23, 0),
512            TimeOfDay::new(0, 10),
513            TimeOfDay::new(12, 30),
514            TimeOfDay::new(0, 0),
515        ];
516        times.sort();
517        assert_eq!(
518            times,
519            [
520                TimeOfDay::new(0, 0),
521                TimeOfDay::new(0, 10),
522                TimeOfDay::new(12, 30),
523                TimeOfDay::new(23, 0),
524            ]
525        );
526        assert!(TimeOfDay::new(20, 0) < TimeOfDay::new(20, 1));
527        assert_eq!(times.iter().max(), Some(&TimeOfDay::new(23, 0)));
528    }
529
530    #[test]
531    fn replacing_keeps_what_it_is_not_given_and_the_period_follows_the_hour() {
532        let cell = AppCell::new();
533        let app = cell.borrow();
534        let time = TimeOfDay::new(9, 30);
535        assert_eq!(time.replacing(Some(21), None), TimeOfDay::new(21, 30));
536        assert_eq!(time.replacing(None, Some(5)), TimeOfDay::new(9, 5));
537        assert_eq!(time.replacing(None, None), time);
538        assert_eq!(time.period(), DayPeriod::Am);
539        assert_eq!(time.period_offset(), 0);
540        assert_eq!(TimeOfDay::new(12, 0).period(), DayPeriod::Pm);
541        assert_eq!(TimeOfDay::new(21, 0).period_offset(), 12);
542        assert_eq!(
543            TimeOfDay::from_date_time(
544                &app,
545                &DateTime::new_with_time(&app, 2018, 10, 20, 16, 30, 4, 0, 0)
546            ),
547            TimeOfDay::new(16, 30)
548        );
549        assert_eq!(format!("{:?}", TimeOfDay::new(7, 5)), "TimeOfDay(07:05)");
550        assert_eq!(format!("{:?}", TimeOfDay::new(23, 45)), "TimeOfDay(23:45)");
551    }
552
553    /// time_test.dart's `_RestorableWidget`.
554    #[derive(Debug)]
555    struct RestorableWidget {
556        key: KeyRef,
557    }
558
559    impl StatefulWidget for RestorableWidget {
560        type State = RestorableWidgetState;
561
562        fn key(&self) -> Option<&KeyRef> {
563            Some(&self.key)
564        }
565
566        fn create_state(&self) -> RestorableWidgetState {
567            RestorableWidgetState {
568                state: StateData::new(),
569                restoration: RestorationMixinData::new(),
570                time_of_day: None,
571            }
572        }
573    }
574
575    struct RestorableWidgetState {
576        state: StateData<RestorableWidget>,
577        restoration: RestorationMixinData,
578        time_of_day: Option<Ref<RestorableTimeOfDay>>,
579    }
580
581    impl RestorableWidgetState {
582        fn time_of_day(self: Handle<Self>, app: &App) -> Ref<RestorableTimeOfDay> {
583            app.get(self).time_of_day.clone().expect("init_state ran")
584        }
585
586        fn set_properties(self: Handle<Self>, app: &mut App, callback: impl FnOnce(&mut App)) {
587            callback(app);
588            self.set_state(app, |_| {});
589        }
590    }
591
592    impl RestorationMixin for RestorableWidgetState {
593        waft_widgets::restoration_mixin_accessors!();
594
595        fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
596            Some("widget")
597        }
598
599        fn restore_state(
600            self: Handle<Self>,
601            app: &mut App,
602            _old_bucket: Option<Handle<RestorationBucket>>,
603            _initial_restore: bool,
604        ) {
605            let time_of_day = self.time_of_day(app);
606            self.register_for_restoration(app, time_of_day.as_property(), "time_of_day");
607        }
608    }
609
610    impl State for RestorableWidgetState {
611        type Widget = RestorableWidget;
612        waft_widgets::state_accessors!();
613
614        fn init_state(self: Handle<Self>, app: &mut App) {
615            let time_of_day = RestorableTimeOfDay::new(app, TimeOfDay::new(10, 5));
616            app.get_mut(self).time_of_day = Some(time_of_day);
617        }
618
619        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
620            self.did_change_dependencies_restoration(app);
621        }
622
623        fn dispose(self: Handle<Self>, app: &mut App) {
624            let time_of_day = self.time_of_day(app);
625            RestorableProperty::dispose(time_of_day.handle(), app);
626            self.dispose_restoration(app);
627        }
628
629        fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
630            SizedBox::shrink().into_widget()
631        }
632    }
633
634    /// Mounts a `_RestorableWidget`, under a root restoration scope when `in_scope`, and hands
635    /// back its state.
636    fn mount(tester: &mut WidgetTester, in_scope: bool) -> Handle<RestorableWidgetState> {
637        let key = GlobalKey::new();
638        let widget = RestorableWidget {
639            key: key.clone().into(),
640        };
641        let root = if in_scope {
642            RootRestorationScope::new(Some("root-child".to_string()), widget).into_widget()
643        } else {
644            widget.into_widget()
645        };
646        tester.pump_widget(root);
647        key.current_state::<RestorableWidgetState>(&tester.cell.borrow_mut())
648            .expect("a _RestorableWidgetState")
649    }
650
651    fn value(app: &App, state: Handle<RestorableWidgetState>) -> TimeOfDay {
652        *RestorableValue::value(state.time_of_day(app).handle(), app)
653    }
654
655    // time_test.dart 'RestorableTimeOfDay tests: value is not accessible when not registered'.
656    #[test]
657    #[should_panic(expected = "is_registered")]
658    fn value_is_not_accessible_when_not_registered() {
659        let cell = AppCell::new();
660        let mut app = cell.borrow_mut();
661        let property = RestorableTimeOfDay::new(&mut app, TimeOfDay::new(20, 4));
662        RestorableValue::value(property.handle(), &app);
663    }
664
665    /// Dart's `state.setProperties(() { state.timeOfDay.value = value; })`, then `tester.pump()`.
666    fn set_time_of_day(
667        tester: &mut WidgetTester,
668        state: Handle<RestorableWidgetState>,
669        value: TimeOfDay,
670    ) {
671        tester.update(|app| {
672            state.set_properties(app, |app| state.time_of_day(app).set_value(app, value));
673        });
674        tester.pump();
675    }
676
677    fn current_value(tester: &WidgetTester, state: Handle<RestorableWidgetState>) -> TimeOfDay {
678        value(&tester.cell.borrow(), state)
679    }
680
681    // time_test.dart 'RestorableTimeOfDay tests: work when not in restoration scope'.
682    #[test]
683    fn a_property_works_when_not_in_a_restoration_scope() {
684        test_widgets(|tester| {
685            let state = mount(tester, false);
686
687            // Initialized to default values.
688            assert_eq!(current_value(tester, state), TimeOfDay::new(10, 5));
689
690            // Modify values.
691            set_time_of_day(tester, state, TimeOfDay::new(2, 2));
692
693            assert_eq!(current_value(tester, state), TimeOfDay::new(2, 2));
694        });
695    }
696
697    // time_test.dart 'RestorableTimeOfDay tests: restart and restore'.
698    #[test]
699    fn a_restarted_app_restores_the_time_of_day() {
700        test_widgets(|_| {
701            let mut tester = WidgetTester::restoring(None);
702            let state = mount(&mut tester, true);
703
704            // Initialized to default values.
705            assert_eq!(current_value(&tester, state), TimeOfDay::new(10, 5));
706
707            // Modify values.
708            set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
709
710            assert_eq!(current_value(&tester, state), TimeOfDay::new(2, 2));
711
712            // Restores to previous values.
713            let mut restarted = WidgetTester::restoring(tester.restoration_data());
714            let restarted_state = mount(&mut restarted, true);
715            assert_eq!(
716                current_value(&restarted, restarted_state),
717                TimeOfDay::new(2, 2)
718            );
719        });
720    }
721
722    // time_test.dart 'RestorableTimeOfDay tests: restore to older state'.
723    #[test]
724    fn a_property_restores_to_older_data_and_to_its_default_from_empty_data() {
725        test_widgets(|_| {
726            let mut tester = WidgetTester::restoring(None);
727            let state = mount(&mut tester, true);
728
729            // Modify values.
730            set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
731
732            let restoration_data = tester.restoration_data();
733
734            // Modify values.
735            set_time_of_day(&mut tester, state, TimeOfDay::new(4, 4));
736
737            // Restore to previous.
738            tester.update(|app| {
739                let manager = RestorationManager::instance(app);
740                manager.handle_restoration_update_from_engine(app, true, restoration_data);
741            });
742            tester.pump();
743            assert_eq!(current_value(&tester, state), TimeOfDay::new(2, 2));
744
745            // Restore to empty data will re-initialize to default values.
746            tester.update(|app| {
747                let manager = RestorationManager::instance(app);
748                manager.handle_restoration_update_from_engine(
749                    app,
750                    true,
751                    Some(RestorationMap::new()),
752                );
753            });
754            tester.pump();
755            assert_eq!(current_value(&tester, state), TimeOfDay::new(10, 5));
756        });
757    }
758
759    // time_test.dart 'RestorableTimeOfDay tests: call notifiers when value changes'.
760    #[test]
761    fn a_property_notifies_only_when_its_value_changes() {
762        test_widgets(|_| {
763            let mut tester = WidgetTester::restoring(None);
764            let state = mount(&mut tester, true);
765
766            let notify_log = Rc::new(RefCell::new(Vec::<&str>::new()));
767            tester.update(|app| {
768                state.time_of_day(app).add_listener(app, {
769                    let notify_log = Rc::clone(&notify_log);
770                    Listener::new(move |_app| notify_log.borrow_mut().push("hello world"))
771                });
772                state.set_properties(app, |app| {
773                    state.time_of_day(app).set_value(app, TimeOfDay::new(2, 2));
774                });
775            });
776            assert_eq!(*notify_log.borrow(), ["hello world"]);
777            notify_log.borrow_mut().clear();
778            tester.pump();
779
780            // Does not notify when set to same value.
781            set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
782
783            assert!(notify_log.borrow().is_empty());
784        });
785    }
786
787    #[test]
788    fn the_restoration_data_is_the_minute_then_the_hour() {
789        test_widgets(|_| {
790            let mut tester = WidgetTester::restoring(None);
791            let state = mount(&mut tester, true);
792            set_time_of_day(&mut tester, state, TimeOfDay::new(2, 7));
793            assert_eq!(
794                tester.update(|app| RestorableProperty::to_primitives(
795                    state.time_of_day(app).handle(),
796                    app
797                )),
798                RestorationData::List(vec![RestorationData::Int(7), RestorationData::Int(2)])
799            );
800            assert!(tester.restoration_data().is_some());
801        });
802    }
803}