use std::cmp::Ordering;
use std::fmt;
use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, DateTime, Handle, Ref};
use waft_services::RestorationData;
use waft_widgets::{
BuildContext, MediaQuery, RestorableProperty, RestorablePropertyData, RestorableValue,
RestorableValueData, debug_check_has_media_query,
};
use crate::debug::debug_check_has_material_localizations;
use crate::material_localizations::MaterialLocalizations;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DayPeriod {
Am,
Pm,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeOfDay {
pub hour: i32,
pub minute: i32,
}
impl TimeOfDay {
pub const fn new(hour: i32, minute: i32) -> TimeOfDay {
TimeOfDay { hour, minute }
}
pub fn now(app: &App) -> TimeOfDay {
TimeOfDay::from_date_time(app, &DateTime::now())
}
pub fn from_date_time(app: &App, time: &DateTime) -> TimeOfDay {
TimeOfDay {
hour: time.hour(app),
minute: time.minute(app),
}
}
pub const HOURS_PER_DAY: i32 = 24;
pub const HOURS_PER_PERIOD: i32 = 12;
pub const MINUTES_PER_HOUR: i32 = 60;
pub fn replacing(&self, hour: Option<i32>, minute: Option<i32>) -> TimeOfDay {
debug_assert!(hour.is_none_or(|hour| (0..Self::HOURS_PER_DAY).contains(&hour)));
debug_assert!(minute.is_none_or(|minute| (0..Self::MINUTES_PER_HOUR).contains(&minute)));
TimeOfDay::new(hour.unwrap_or(self.hour), minute.unwrap_or(self.minute))
}
pub fn period(&self) -> DayPeriod {
if self.hour < Self::HOURS_PER_PERIOD {
DayPeriod::Am
} else {
DayPeriod::Pm
}
}
pub fn hour_of_period(&self) -> i32 {
if self.hour == 0 || self.hour == 12 {
12
} else {
self.hour - self.period_offset()
}
}
pub fn period_offset(&self) -> i32 {
if self.period() == DayPeriod::Am {
0
} else {
Self::HOURS_PER_PERIOD
}
}
pub fn format(&self, app: &mut App, context: BuildContext) -> String {
debug_assert!(debug_check_has_media_query(app, context));
debug_assert!(debug_check_has_material_localizations(app, context));
let localizations = <dyn MaterialLocalizations>::of(app, context);
localizations
.format_time_of_day(self, MediaQuery::always_use_24_hour_format_of(app, context))
}
pub fn is_before(&self, other: &TimeOfDay) -> bool {
self.compare_to(other) == Ordering::Less
}
pub fn is_after(&self, other: &TimeOfDay) -> bool {
self.compare_to(other) == Ordering::Greater
}
pub fn is_at_same_time_as(&self, other: &TimeOfDay) -> bool {
self.compare_to(other) == Ordering::Equal
}
pub fn compare_to(&self, other: &TimeOfDay) -> Ordering {
let hour_comparison = self.hour.cmp(&other.hour);
if hour_comparison == Ordering::Equal {
self.minute.cmp(&other.minute)
} else {
hour_comparison
}
}
}
impl Ord for TimeOfDay {
fn cmp(&self, other: &TimeOfDay) -> Ordering {
self.compare_to(other)
}
}
impl PartialOrd for TimeOfDay {
fn partial_cmp(&self, other: &TimeOfDay) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl fmt::Debug for TimeOfDay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn add_leading_zero_if_needed(value: i32) -> String {
if value < 10 {
return format!("0{value}");
}
value.to_string()
}
let hour_label = add_leading_zero_if_needed(self.hour);
let minute_label = add_leading_zero_if_needed(self.minute);
write!(f, "TimeOfDay({hour_label}:{minute_label})")
}
}
pub struct RestorableTimeOfDay {
change_notifier: ChangeNotifierData,
property: RestorablePropertyData,
value: RestorableValueData<TimeOfDay>,
default_value: TimeOfDay,
}
impl RestorableTimeOfDay {
pub fn new(app: &mut App, default_value: TimeOfDay) -> Ref<RestorableTimeOfDay> {
app.create(RestorableTimeOfDay {
change_notifier: ChangeNotifierData::new(),
property: RestorablePropertyData::new(),
value: RestorableValueData::new(),
default_value,
})
}
}
impl ChangeNotifier for RestorableTimeOfDay {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl RestorableProperty for RestorableTimeOfDay {
type Value = TimeOfDay;
waft_widgets::restorable_property_accessors!();
fn create_default_value(self: Handle<Self>, app: &mut App) -> TimeOfDay {
app.get(self).default_value
}
fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> TimeOfDay {
let _ = app;
let time_data = data
.as_list()
.expect("the restoration data of a TimeOfDay property is a list");
let int_at = |index: usize| {
let value = time_data[index]
.as_int()
.expect("the restoration data of a TimeOfDay property holds ints");
i32::try_from(value).expect("an hour or a minute")
};
TimeOfDay::new(int_at(1), int_at(0))
}
fn init_with_value(self: Handle<Self>, app: &mut App, value: TimeOfDay) {
RestorableValue::init_with_value(self, app, value);
}
fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
let value = RestorableValue::value(self, app);
RestorationData::List(vec![
RestorationData::Int(i64::from(value.minute)),
RestorationData::Int(i64::from(value.hour)),
])
}
}
impl RestorableValue for RestorableTimeOfDay {
waft_widgets::restorable_value_accessors!();
fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<TimeOfDay>) {
let _ = old_value;
self.notify_listeners(app);
}
}
#[allow(
non_camel_case_types,
reason = "Dart's names are ICU patterns, where the case of a letter is its meaning"
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TimeOfDayFormat {
HH_colon_mm,
HH_dot_mm,
FrenchCanadian,
H_colon_mm,
h_colon_mm_space_a,
a_space_h_colon_mm,
}
#[allow(
non_camel_case_types,
clippy::upper_case_acronyms,
reason = "Dart's names are ICU patterns, where `H` and `h` are different hours"
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HourFormat {
HH,
H,
h,
}
pub fn hour_format(of: TimeOfDayFormat) -> HourFormat {
match of {
TimeOfDayFormat::h_colon_mm_space_a | TimeOfDayFormat::a_space_h_colon_mm => HourFormat::h,
TimeOfDayFormat::H_colon_mm => HourFormat::H,
TimeOfDayFormat::HH_dot_mm
| TimeOfDayFormat::HH_colon_mm
| TimeOfDayFormat::FrenchCanadian => HourFormat::HH,
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use waft_foundation::{AppCell, Listenable, Listener};
use waft_services::{RestorationBucket, RestorationManager, RestorationMap};
use waft_widgets::testing::{WidgetTester, test_widgets};
use waft_widgets::{
Builder, GlobalKey, IntoWidget, KeyRef, MediaQueryData, RestorationMixin,
RestorationMixinData, RootRestorationScope, SizedBox, State, StateData, StatefulWidget,
WidgetRef,
};
use super::*;
use crate::material_localizations::tests::us_english;
#[test]
fn hour_format_names_the_hours_of_each_time_of_day_format() {
for format in [
TimeOfDayFormat::h_colon_mm_space_a,
TimeOfDayFormat::a_space_h_colon_mm,
] {
assert_eq!(hour_format(format), HourFormat::h, "for {format:?}");
}
assert_eq!(hour_format(TimeOfDayFormat::H_colon_mm), HourFormat::H);
for format in [
TimeOfDayFormat::HH_dot_mm,
TimeOfDayFormat::HH_colon_mm,
TimeOfDayFormat::FrenchCanadian,
] {
assert_eq!(hour_format(format), HourFormat::HH, "for {format:?}");
}
}
#[test]
fn format_respects_always_use_24_hour_format() {
let pump_test = |always_use_24_hour_format: bool| {
let mut formatted = String::new();
test_widgets(|tester| {
let formatted_value = Rc::new(RefCell::new(String::new()));
let probe = Builder::new({
let formatted_value = Rc::clone(&formatted_value);
move |app, context| {
*formatted_value.borrow_mut() = TimeOfDay::new(7, 0).format(app, context);
SizedBox::shrink().into_widget()
}
});
tester.pump_widget(us_english(
MediaQuery::new(
MediaQueryData::new().always_use_24_hour_format(always_use_24_hour_format),
probe,
)
.into_widget(),
));
formatted = formatted_value.take();
});
formatted
};
assert_eq!(pump_test(false), "7:00 AM");
assert_eq!(pump_test(true), "07:00");
}
#[test]
fn hour_of_period_counts_from_twelve() {
let expected = [
12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
];
for (hour, hour_of_period) in (0..24).zip(expected) {
assert_eq!(
TimeOfDay::new(hour, 0).hour_of_period(),
hour_of_period,
"hour {hour}"
);
}
}
#[test]
fn a_time_of_day_compares_by_hour_then_minute() {
let time = TimeOfDay::new;
assert_eq!(time(0, 0).compare_to(&time(1, 0)), Ordering::Less);
assert_eq!(time(20, 0).compare_to(&time(20, 1)), Ordering::Less);
assert_eq!(time(0, 0).compare_to(&time(0, 0)), Ordering::Equal);
assert_eq!(time(1, 0).compare_to(&time(0, 0)), Ordering::Greater);
assert_eq!(time(20, 1).compare_to(&time(20, 0)), Ordering::Greater);
assert!(time(0, 0).is_before(&time(1, 0)));
assert!(time(0, 0).is_before(&time(23, 0)));
assert!(time(0, 0).is_before(&time(0, 10)));
assert!(!time(0, 0).is_before(&time(0, 0)));
assert!(!time(1, 0).is_before(&time(0, 0)));
assert!(!time(23, 0).is_before(&time(0, 0)));
assert!(!time(0, 10).is_before(&time(0, 0)));
assert!(!time(0, 0).is_after(&time(1, 0)));
assert!(!time(0, 0).is_after(&time(23, 0)));
assert!(!time(0, 0).is_after(&time(0, 10)));
assert!(!time(0, 0).is_after(&time(0, 0)));
assert!(time(1, 0).is_after(&time(0, 0)));
assert!(time(23, 0).is_after(&time(0, 0)));
assert!(time(0, 10).is_after(&time(0, 0)));
assert!(!time(0, 0).is_at_same_time_as(&time(1, 0)));
assert!(!time(0, 0).is_at_same_time_as(&time(0, 10)));
assert!(time(0, 0).is_at_same_time_as(&time(0, 0)));
assert!(!time(1, 0).is_at_same_time_as(&time(0, 0)));
assert!(!time(0, 10).is_at_same_time_as(&time(0, 0)));
}
#[test]
fn a_time_of_day_sorts_as_it_compares() {
let mut times = vec![
TimeOfDay::new(23, 0),
TimeOfDay::new(0, 10),
TimeOfDay::new(12, 30),
TimeOfDay::new(0, 0),
];
times.sort();
assert_eq!(
times,
[
TimeOfDay::new(0, 0),
TimeOfDay::new(0, 10),
TimeOfDay::new(12, 30),
TimeOfDay::new(23, 0),
]
);
assert!(TimeOfDay::new(20, 0) < TimeOfDay::new(20, 1));
assert_eq!(times.iter().max(), Some(&TimeOfDay::new(23, 0)));
}
#[test]
fn replacing_keeps_what_it_is_not_given_and_the_period_follows_the_hour() {
let cell = AppCell::new();
let app = cell.borrow();
let time = TimeOfDay::new(9, 30);
assert_eq!(time.replacing(Some(21), None), TimeOfDay::new(21, 30));
assert_eq!(time.replacing(None, Some(5)), TimeOfDay::new(9, 5));
assert_eq!(time.replacing(None, None), time);
assert_eq!(time.period(), DayPeriod::Am);
assert_eq!(time.period_offset(), 0);
assert_eq!(TimeOfDay::new(12, 0).period(), DayPeriod::Pm);
assert_eq!(TimeOfDay::new(21, 0).period_offset(), 12);
assert_eq!(
TimeOfDay::from_date_time(
&app,
&DateTime::new_with_time(&app, 2018, 10, 20, 16, 30, 4, 0, 0)
),
TimeOfDay::new(16, 30)
);
assert_eq!(format!("{:?}", TimeOfDay::new(7, 5)), "TimeOfDay(07:05)");
assert_eq!(format!("{:?}", TimeOfDay::new(23, 45)), "TimeOfDay(23:45)");
}
#[derive(Debug)]
struct RestorableWidget {
key: KeyRef,
}
impl StatefulWidget for RestorableWidget {
type State = RestorableWidgetState;
fn key(&self) -> Option<&KeyRef> {
Some(&self.key)
}
fn create_state(&self) -> RestorableWidgetState {
RestorableWidgetState {
state: StateData::new(),
restoration: RestorationMixinData::new(),
time_of_day: None,
}
}
}
struct RestorableWidgetState {
state: StateData<RestorableWidget>,
restoration: RestorationMixinData,
time_of_day: Option<Ref<RestorableTimeOfDay>>,
}
impl RestorableWidgetState {
fn time_of_day(self: Handle<Self>, app: &App) -> Ref<RestorableTimeOfDay> {
app.get(self).time_of_day.clone().expect("init_state ran")
}
fn set_properties(self: Handle<Self>, app: &mut App, callback: impl FnOnce(&mut App)) {
callback(app);
self.set_state(app, |_| {});
}
}
impl RestorationMixin for RestorableWidgetState {
waft_widgets::restoration_mixin_accessors!();
fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
Some("widget")
}
fn restore_state(
self: Handle<Self>,
app: &mut App,
_old_bucket: Option<Handle<RestorationBucket>>,
_initial_restore: bool,
) {
let time_of_day = self.time_of_day(app);
self.register_for_restoration(app, time_of_day.as_property(), "time_of_day");
}
}
impl State for RestorableWidgetState {
type Widget = RestorableWidget;
waft_widgets::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let time_of_day = RestorableTimeOfDay::new(app, TimeOfDay::new(10, 5));
app.get_mut(self).time_of_day = Some(time_of_day);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
self.did_change_dependencies_restoration(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let time_of_day = self.time_of_day(app);
RestorableProperty::dispose(time_of_day.handle(), app);
self.dispose_restoration(app);
}
fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
SizedBox::shrink().into_widget()
}
}
fn mount(tester: &mut WidgetTester, in_scope: bool) -> Handle<RestorableWidgetState> {
let key = GlobalKey::new();
let widget = RestorableWidget {
key: key.clone().into(),
};
let root = if in_scope {
RootRestorationScope::new(Some("root-child".to_string()), widget).into_widget()
} else {
widget.into_widget()
};
tester.pump_widget(root);
key.current_state::<RestorableWidgetState>(&tester.cell.borrow_mut())
.expect("a _RestorableWidgetState")
}
fn value(app: &App, state: Handle<RestorableWidgetState>) -> TimeOfDay {
*RestorableValue::value(state.time_of_day(app).handle(), app)
}
#[test]
#[should_panic(expected = "is_registered")]
fn value_is_not_accessible_when_not_registered() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let property = RestorableTimeOfDay::new(&mut app, TimeOfDay::new(20, 4));
RestorableValue::value(property.handle(), &app);
}
fn set_time_of_day(
tester: &mut WidgetTester,
state: Handle<RestorableWidgetState>,
value: TimeOfDay,
) {
tester.update(|app| {
state.set_properties(app, |app| state.time_of_day(app).set_value(app, value));
});
tester.pump();
}
fn current_value(tester: &WidgetTester, state: Handle<RestorableWidgetState>) -> TimeOfDay {
value(&tester.cell.borrow(), state)
}
#[test]
fn a_property_works_when_not_in_a_restoration_scope() {
test_widgets(|tester| {
let state = mount(tester, false);
assert_eq!(current_value(tester, state), TimeOfDay::new(10, 5));
set_time_of_day(tester, state, TimeOfDay::new(2, 2));
assert_eq!(current_value(tester, state), TimeOfDay::new(2, 2));
});
}
#[test]
fn a_restarted_app_restores_the_time_of_day() {
test_widgets(|_| {
let mut tester = WidgetTester::restoring(None);
let state = mount(&mut tester, true);
assert_eq!(current_value(&tester, state), TimeOfDay::new(10, 5));
set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
assert_eq!(current_value(&tester, state), TimeOfDay::new(2, 2));
let mut restarted = WidgetTester::restoring(tester.restoration_data());
let restarted_state = mount(&mut restarted, true);
assert_eq!(
current_value(&restarted, restarted_state),
TimeOfDay::new(2, 2)
);
});
}
#[test]
fn a_property_restores_to_older_data_and_to_its_default_from_empty_data() {
test_widgets(|_| {
let mut tester = WidgetTester::restoring(None);
let state = mount(&mut tester, true);
set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
let restoration_data = tester.restoration_data();
set_time_of_day(&mut tester, state, TimeOfDay::new(4, 4));
tester.update(|app| {
let manager = RestorationManager::instance(app);
manager.handle_restoration_update_from_engine(app, true, restoration_data);
});
tester.pump();
assert_eq!(current_value(&tester, state), TimeOfDay::new(2, 2));
tester.update(|app| {
let manager = RestorationManager::instance(app);
manager.handle_restoration_update_from_engine(
app,
true,
Some(RestorationMap::new()),
);
});
tester.pump();
assert_eq!(current_value(&tester, state), TimeOfDay::new(10, 5));
});
}
#[test]
fn a_property_notifies_only_when_its_value_changes() {
test_widgets(|_| {
let mut tester = WidgetTester::restoring(None);
let state = mount(&mut tester, true);
let notify_log = Rc::new(RefCell::new(Vec::<&str>::new()));
tester.update(|app| {
state.time_of_day(app).add_listener(app, {
let notify_log = Rc::clone(¬ify_log);
Listener::new(move |_app| notify_log.borrow_mut().push("hello world"))
});
state.set_properties(app, |app| {
state.time_of_day(app).set_value(app, TimeOfDay::new(2, 2));
});
});
assert_eq!(*notify_log.borrow(), ["hello world"]);
notify_log.borrow_mut().clear();
tester.pump();
set_time_of_day(&mut tester, state, TimeOfDay::new(2, 2));
assert!(notify_log.borrow().is_empty());
});
}
#[test]
fn the_restoration_data_is_the_minute_then_the_hour() {
test_widgets(|_| {
let mut tester = WidgetTester::restoring(None);
let state = mount(&mut tester, true);
set_time_of_day(&mut tester, state, TimeOfDay::new(2, 7));
assert_eq!(
tester.update(|app| RestorableProperty::to_primitives(
state.time_of_day(app).handle(),
app
)),
RestorationData::List(vec![RestorationData::Int(7), RestorationData::Int(2)])
);
assert!(tester.restoration_data().is_some());
});
}
}