1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum DayPeriod {
22 Am,
24
25 Pm,
27}
28
29#[derive(Clone, Copy, PartialEq, Eq, Hash)]
57pub struct TimeOfDay {
58 pub hour: i32,
60
61 pub minute: i32,
63}
64
65impl TimeOfDay {
66 pub const fn new(hour: i32, minute: i32) -> TimeOfDay {
71 TimeOfDay { hour, minute }
72 }
73
74 pub fn now(app: &App) -> TimeOfDay {
76 TimeOfDay::from_date_time(app, &DateTime::now())
77 }
78
79 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 pub const HOURS_PER_DAY: i32 = 24;
92
93 pub const HOURS_PER_PERIOD: i32 = 12;
95
96 pub const MINUTES_PER_HOUR: i32 = 60;
98
99 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 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 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 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 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 pub fn is_before(&self, other: &TimeOfDay) -> bool {
151 self.compare_to(other) == Ordering::Less
152 }
153
154 pub fn is_after(&self, other: &TimeOfDay) -> bool {
159 self.compare_to(other) == Ordering::Greater
160 }
161
162 pub fn is_at_same_time_as(&self, other: &TimeOfDay) -> bool {
167 self.compare_to(other) == Ordering::Equal
168 }
169
170 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
191impl 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
220pub struct RestorableTimeOfDay {
229 change_notifier: ChangeNotifierData,
230 property: RestorablePropertyData,
231 value: RestorableValueData<TimeOfDay>,
232 default_value: TimeOfDay,
233}
234
235impl RestorableTimeOfDay {
236 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#[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 HH_colon_mm,
321
322 HH_dot_mm,
328
329 FrenchCanadian,
334
335 H_colon_mm,
341
342 h_colon_mm_space_a,
350
351 a_space_h_colon_mm,
359}
360
361#[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 HH,
371
372 H,
374
375 h,
378}
379
380pub 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 #[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 #[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 #[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 #[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 #[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 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 #[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 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 #[test]
683 fn a_property_works_when_not_in_a_restoration_scope() {
684 test_widgets(|tester| {
685 let state = mount(tester, false);
686
687 assert_eq!(current_value(tester, state), TimeOfDay::new(10, 5));
689
690 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 #[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 assert_eq!(current_value(&tester, state), TimeOfDay::new(10, 5));
706
707 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 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 #[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 set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
731
732 let restoration_data = tester.restoration_data();
733
734 set_time_of_day(&mut tester, state, TimeOfDay::new(4, 4));
736
737 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 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 #[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(¬ify_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 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}