1use std::fmt::Debug;
8
9use waft_foundation::{
10 App, ChangeNotifier, ChangeNotifierData, DateTime, Handle, Listenable, Listener,
11};
12use waft_services::{RestorationData, TextEditingValue};
13
14use crate::widgets::editable_text::{TextEditingController, TextEditingControllerLeaf};
15use crate::widgets::restoration::{RestorableProperty, RestorablePropertyData};
16use waft_foundation::Ref;
17
18pub struct RestorableValueData<T> {
24 value: Option<T>,
25}
26
27impl<T> RestorableValueData<T> {
28 pub fn new() -> RestorableValueData<T> {
30 RestorableValueData { value: None }
31 }
32}
33
34impl<T> Default for RestorableValueData<T> {
35 fn default() -> RestorableValueData<T> {
36 RestorableValueData::new()
37 }
38}
39
40#[macro_export]
42macro_rules! restorable_value_accessors {
43 () => {
44 fn restorable_value_data(
45 self: ::waft_foundation::Handle<Self>,
46 app: &::waft_foundation::App,
47 ) -> &$crate::RestorableValueData<Self::Value> {
48 &app.get(self).value
49 }
50
51 fn restorable_value_data_mut(
52 self: ::waft_foundation::Handle<Self>,
53 app: &mut ::waft_foundation::App,
54 ) -> &mut $crate::RestorableValueData<Self::Value> {
55 &mut app.get_mut(self).value
56 }
57 };
58}
59
60pub trait RestorableValue: RestorableProperty<Value: Clone + PartialEq> {
115 fn restorable_value_data(self: Handle<Self>, app: &App) -> &RestorableValueData<Self::Value>;
118
119 fn restorable_value_data_mut(
121 self: Handle<Self>,
122 app: &mut App,
123 ) -> &mut RestorableValueData<Self::Value>;
124
125 fn value(self: Handle<Self>, app: &App) -> &Self::Value {
135 debug_assert!(RestorableProperty::is_registered(self, app));
136 self.restorable_value_data(app)
137 .value
138 .as_ref()
139 .expect("init_with_value runs at registration")
140 }
141
142 fn set_value(self: Handle<Self>, app: &mut App, new_value: Self::Value) {
145 debug_assert!(RestorableProperty::is_registered(self, app));
146 debug_assert!(self.debug_assert_valid_value(app, &new_value));
147 if self.restorable_value_data(app).value.as_ref() != Some(&new_value) {
148 let old_value = self.restorable_value_data_mut(app).value.replace(new_value);
149 RestorableValue::did_update_value(self, app, old_value);
150 }
151 }
152
153 fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
157 self.restorable_value_data_mut(app).value = Some(value);
158 }
159
160 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Self::Value>);
168
169 fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &Self::Value) -> bool {
174 let _ = (self, app, new_value);
175 true
176 }
177}
178
179pub trait RestorablePrimitive: Clone + PartialEq + 'static {
188 fn from_restoration_data(data: &RestorationData) -> Self;
191
192 fn to_restoration_data(&self) -> RestorationData;
194}
195
196impl RestorablePrimitive for bool {
197 fn from_restoration_data(data: &RestorationData) -> bool {
198 data.as_bool()
199 .expect("the restoration data of a bool property is a bool")
200 }
201
202 fn to_restoration_data(&self) -> RestorationData {
203 RestorationData::Bool(*self)
204 }
205}
206
207impl RestorablePrimitive for i64 {
208 fn from_restoration_data(data: &RestorationData) -> i64 {
209 data.as_int()
210 .expect("the restoration data of an int property is an int")
211 }
212
213 fn to_restoration_data(&self) -> RestorationData {
214 RestorationData::Int(*self)
215 }
216}
217
218impl RestorablePrimitive for f64 {
219 fn from_restoration_data(data: &RestorationData) -> f64 {
220 data.as_double()
221 .expect("the restoration data of a double property is a double")
222 }
223
224 fn to_restoration_data(&self) -> RestorationData {
225 RestorationData::Double(*self)
226 }
227}
228
229impl RestorablePrimitive for String {
230 fn from_restoration_data(data: &RestorationData) -> String {
231 data.as_str()
232 .expect("the restoration data of a String property is a String")
233 .to_string()
234 }
235
236 fn to_restoration_data(&self) -> RestorationData {
237 RestorationData::String(self.clone())
238 }
239}
240
241impl<T: RestorablePrimitive> RestorablePrimitive for Option<T> {
242 fn from_restoration_data(data: &RestorationData) -> Option<T> {
243 (!data.is_null()).then(|| T::from_restoration_data(data))
244 }
245
246 fn to_restoration_data(&self) -> RestorationData {
247 self.as_ref()
248 .map_or(RestorationData::Null, T::to_restoration_data)
249 }
250}
251
252pub trait RestorableNumValue: RestorablePrimitive {}
254
255impl RestorableNumValue for i64 {}
256
257impl RestorableNumValue for f64 {}
258
259pub struct RestorablePrimitiveValueData<T> {
262 default_value: T,
263}
264
265impl<T> RestorablePrimitiveValueData<T> {
266 pub fn new(default_value: T) -> RestorablePrimitiveValueData<T> {
268 RestorablePrimitiveValueData { default_value }
269 }
270}
271
272#[macro_export]
275macro_rules! restorable_primitive_value_accessors {
276 () => {
277 fn restorable_primitive_value_data(
278 self: ::waft_foundation::Handle<Self>,
279 app: &::waft_foundation::App,
280 ) -> &$crate::RestorablePrimitiveValueData<Self::Value> {
281 &app.get(self).primitive
282 }
283
284 fn restorable_primitive_value_data_mut(
285 self: ::waft_foundation::Handle<Self>,
286 app: &mut ::waft_foundation::App,
287 ) -> &mut $crate::RestorablePrimitiveValueData<Self::Value> {
288 &mut app.get_mut(self).primitive
289 }
290 };
291}
292
293pub trait RestorablePrimitiveValueN: RestorableValue<Value: RestorablePrimitive> {
298 fn restorable_primitive_value_data(
301 self: Handle<Self>,
302 app: &App,
303 ) -> &RestorablePrimitiveValueData<Self::Value>;
304
305 fn restorable_primitive_value_data_mut(
307 self: Handle<Self>,
308 app: &mut App,
309 ) -> &mut RestorablePrimitiveValueData<Self::Value>;
310
311 fn create_default_value(self: Handle<Self>, app: &mut App) -> Self::Value {
313 self.restorable_primitive_value_data(app)
314 .default_value
315 .clone()
316 }
317
318 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Self::Value>) {
320 let _ = old_value;
321 self.notify_listeners(app);
322 }
323
324 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Self::Value {
326 let _ = app;
327 Self::Value::from_restoration_data(data)
328 }
329
330 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
332 RestorableValue::value(self, app).to_restoration_data()
333 }
334}
335
336pub trait RestorablePrimitiveValue: RestorablePrimitiveValueN {}
344
345pub struct RestorableNum<T: RestorableNumValue> {
365 change_notifier: ChangeNotifierData,
366 property: RestorablePropertyData,
367 value: RestorableValueData<T>,
368 primitive: RestorablePrimitiveValueData<T>,
369}
370
371impl<T: RestorableNumValue> RestorableNum<T> {
372 pub fn new(app: &mut App, default_value: T) -> Ref<RestorableNum<T>> {
377 app.create(RestorableNum {
378 change_notifier: ChangeNotifierData::new(),
379 property: RestorablePropertyData::new(),
380 value: RestorableValueData::new(),
381 primitive: RestorablePrimitiveValueData::new(default_value),
382 })
383 }
384}
385
386impl<T: RestorableNumValue> ChangeNotifier for RestorableNum<T> {
387 fn change_notifier_data(&self) -> &ChangeNotifierData {
388 &self.change_notifier
389 }
390
391 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
392 &mut self.change_notifier
393 }
394}
395
396impl<T: RestorableNumValue> RestorableProperty for RestorableNum<T> {
397 type Value = T;
398 crate::restorable_property_accessors!();
399
400 fn create_default_value(self: Handle<Self>, app: &mut App) -> T {
401 RestorablePrimitiveValueN::create_default_value(self, app)
402 }
403
404 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> T {
405 RestorablePrimitiveValueN::from_primitives(self, app, data)
406 }
407
408 fn init_with_value(self: Handle<Self>, app: &mut App, value: T) {
409 RestorableValue::init_with_value(self, app, value);
410 }
411
412 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
413 RestorablePrimitiveValueN::to_primitives(self, app)
414 }
415}
416
417impl<T: RestorableNumValue> RestorableValue for RestorableNum<T> {
418 crate::restorable_value_accessors!();
419
420 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<T>) {
421 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
422 }
423}
424
425impl<T: RestorableNumValue> RestorablePrimitiveValueN for RestorableNum<T> {
426 crate::restorable_primitive_value_accessors!();
427}
428
429impl<T: RestorableNumValue> RestorablePrimitiveValue for RestorableNum<T> {}
430
431pub type RestorableDouble = RestorableNum<f64>;
438
439pub type RestorableInt = RestorableNum<i64>;
446
447pub struct RestorableString {
460 change_notifier: ChangeNotifierData,
461 property: RestorablePropertyData,
462 value: RestorableValueData<String>,
463 primitive: RestorablePrimitiveValueData<String>,
464}
465
466impl RestorableString {
467 pub fn new(app: &mut App, default_value: impl Into<String>) -> Ref<RestorableString> {
472 app.create(RestorableString {
473 change_notifier: ChangeNotifierData::new(),
474 property: RestorablePropertyData::new(),
475 value: RestorableValueData::new(),
476 primitive: RestorablePrimitiveValueData::new(default_value.into()),
477 })
478 }
479}
480
481impl ChangeNotifier for RestorableString {
482 fn change_notifier_data(&self) -> &ChangeNotifierData {
483 &self.change_notifier
484 }
485
486 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
487 &mut self.change_notifier
488 }
489}
490
491impl RestorableProperty for RestorableString {
492 type Value = String;
493 crate::restorable_property_accessors!();
494
495 fn create_default_value(self: Handle<Self>, app: &mut App) -> String {
496 RestorablePrimitiveValueN::create_default_value(self, app)
497 }
498
499 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> String {
500 RestorablePrimitiveValueN::from_primitives(self, app, data)
501 }
502
503 fn init_with_value(self: Handle<Self>, app: &mut App, value: String) {
504 RestorableValue::init_with_value(self, app, value);
505 }
506
507 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
508 RestorablePrimitiveValueN::to_primitives(self, app)
509 }
510}
511
512impl RestorableValue for RestorableString {
513 crate::restorable_value_accessors!();
514
515 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<String>) {
516 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
517 }
518}
519
520impl RestorablePrimitiveValueN for RestorableString {
521 crate::restorable_primitive_value_accessors!();
522}
523
524impl RestorablePrimitiveValue for RestorableString {}
525
526pub struct RestorableBool {
539 change_notifier: ChangeNotifierData,
540 property: RestorablePropertyData,
541 value: RestorableValueData<bool>,
542 primitive: RestorablePrimitiveValueData<bool>,
543}
544
545impl RestorableBool {
546 pub fn new(app: &mut App, default_value: bool) -> Ref<RestorableBool> {
551 app.create(RestorableBool {
552 change_notifier: ChangeNotifierData::new(),
553 property: RestorablePropertyData::new(),
554 value: RestorableValueData::new(),
555 primitive: RestorablePrimitiveValueData::new(default_value),
556 })
557 }
558}
559
560impl ChangeNotifier for RestorableBool {
561 fn change_notifier_data(&self) -> &ChangeNotifierData {
562 &self.change_notifier
563 }
564
565 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
566 &mut self.change_notifier
567 }
568}
569
570impl RestorableProperty for RestorableBool {
571 type Value = bool;
572 crate::restorable_property_accessors!();
573
574 fn create_default_value(self: Handle<Self>, app: &mut App) -> bool {
575 RestorablePrimitiveValueN::create_default_value(self, app)
576 }
577
578 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> bool {
579 RestorablePrimitiveValueN::from_primitives(self, app, data)
580 }
581
582 fn init_with_value(self: Handle<Self>, app: &mut App, value: bool) {
583 RestorableValue::init_with_value(self, app, value);
584 }
585
586 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
587 RestorablePrimitiveValueN::to_primitives(self, app)
588 }
589}
590
591impl RestorableValue for RestorableBool {
592 crate::restorable_value_accessors!();
593
594 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<bool>) {
595 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
596 }
597}
598
599impl RestorablePrimitiveValueN for RestorableBool {
600 crate::restorable_primitive_value_accessors!();
601}
602
603impl RestorablePrimitiveValue for RestorableBool {}
604
605pub struct RestorableBoolN {
618 change_notifier: ChangeNotifierData,
619 property: RestorablePropertyData,
620 value: RestorableValueData<Option<bool>>,
621 primitive: RestorablePrimitiveValueData<Option<bool>>,
622}
623
624impl RestorableBoolN {
625 pub fn new(app: &mut App, default_value: Option<bool>) -> Ref<RestorableBoolN> {
630 app.create(RestorableBoolN {
631 change_notifier: ChangeNotifierData::new(),
632 property: RestorablePropertyData::new(),
633 value: RestorableValueData::new(),
634 primitive: RestorablePrimitiveValueData::new(default_value),
635 })
636 }
637}
638
639impl ChangeNotifier for RestorableBoolN {
640 fn change_notifier_data(&self) -> &ChangeNotifierData {
641 &self.change_notifier
642 }
643
644 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
645 &mut self.change_notifier
646 }
647}
648
649impl RestorableProperty for RestorableBoolN {
650 type Value = Option<bool>;
651 crate::restorable_property_accessors!();
652
653 fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<bool> {
654 RestorablePrimitiveValueN::create_default_value(self, app)
655 }
656
657 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<bool> {
658 RestorablePrimitiveValueN::from_primitives(self, app, data)
659 }
660
661 fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<bool>) {
662 RestorableValue::init_with_value(self, app, value);
663 }
664
665 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
666 RestorablePrimitiveValueN::to_primitives(self, app)
667 }
668}
669
670impl RestorableValue for RestorableBoolN {
671 crate::restorable_value_accessors!();
672
673 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<bool>>) {
674 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
675 }
676}
677
678impl RestorablePrimitiveValueN for RestorableBoolN {
679 crate::restorable_primitive_value_accessors!();
680}
681
682pub struct RestorableNumN<T: RestorableNumValue> {
699 change_notifier: ChangeNotifierData,
700 property: RestorablePropertyData,
701 value: RestorableValueData<Option<T>>,
702 primitive: RestorablePrimitiveValueData<Option<T>>,
703}
704
705impl<T: RestorableNumValue> RestorableNumN<T> {
706 pub fn new(app: &mut App, default_value: Option<T>) -> Ref<RestorableNumN<T>> {
711 app.create(RestorableNumN {
712 change_notifier: ChangeNotifierData::new(),
713 property: RestorablePropertyData::new(),
714 value: RestorableValueData::new(),
715 primitive: RestorablePrimitiveValueData::new(default_value),
716 })
717 }
718}
719
720impl<T: RestorableNumValue> ChangeNotifier for RestorableNumN<T> {
721 fn change_notifier_data(&self) -> &ChangeNotifierData {
722 &self.change_notifier
723 }
724
725 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
726 &mut self.change_notifier
727 }
728}
729
730impl<T: RestorableNumValue> RestorableProperty for RestorableNumN<T> {
731 type Value = Option<T>;
732 crate::restorable_property_accessors!();
733
734 fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<T> {
735 RestorablePrimitiveValueN::create_default_value(self, app)
736 }
737
738 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<T> {
739 RestorablePrimitiveValueN::from_primitives(self, app, data)
740 }
741
742 fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<T>) {
743 RestorableValue::init_with_value(self, app, value);
744 }
745
746 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
747 RestorablePrimitiveValueN::to_primitives(self, app)
748 }
749}
750
751impl<T: RestorableNumValue> RestorableValue for RestorableNumN<T> {
752 crate::restorable_value_accessors!();
753
754 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<T>>) {
755 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
756 }
757}
758
759impl<T: RestorableNumValue> RestorablePrimitiveValueN for RestorableNumN<T> {
760 crate::restorable_primitive_value_accessors!();
761}
762
763pub type RestorableDoubleN = RestorableNumN<f64>;
770
771pub type RestorableIntN = RestorableNumN<i64>;
778
779pub struct RestorableStringN {
792 change_notifier: ChangeNotifierData,
793 property: RestorablePropertyData,
794 value: RestorableValueData<Option<String>>,
795 primitive: RestorablePrimitiveValueData<Option<String>>,
796}
797
798impl RestorableStringN {
799 pub fn new(app: &mut App, default_value: Option<String>) -> Ref<RestorableStringN> {
804 app.create(RestorableStringN {
805 change_notifier: ChangeNotifierData::new(),
806 property: RestorablePropertyData::new(),
807 value: RestorableValueData::new(),
808 primitive: RestorablePrimitiveValueData::new(default_value),
809 })
810 }
811}
812
813impl ChangeNotifier for RestorableStringN {
814 fn change_notifier_data(&self) -> &ChangeNotifierData {
815 &self.change_notifier
816 }
817
818 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
819 &mut self.change_notifier
820 }
821}
822
823impl RestorableProperty for RestorableStringN {
824 type Value = Option<String>;
825 crate::restorable_property_accessors!();
826
827 fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<String> {
828 RestorablePrimitiveValueN::create_default_value(self, app)
829 }
830
831 fn from_primitives(
832 self: Handle<Self>,
833 app: &mut App,
834 data: &RestorationData,
835 ) -> Option<String> {
836 RestorablePrimitiveValueN::from_primitives(self, app, data)
837 }
838
839 fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<String>) {
840 RestorableValue::init_with_value(self, app, value);
841 }
842
843 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
844 RestorablePrimitiveValueN::to_primitives(self, app)
845 }
846}
847
848impl RestorableValue for RestorableStringN {
849 crate::restorable_value_accessors!();
850
851 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<String>>) {
852 RestorablePrimitiveValueN::did_update_value(self, app, old_value);
853 }
854}
855
856impl RestorablePrimitiveValueN for RestorableStringN {
857 crate::restorable_primitive_value_accessors!();
858}
859
860pub struct RestorableDateTime {
872 change_notifier: ChangeNotifierData,
873 property: RestorablePropertyData,
874 value: RestorableValueData<DateTime>,
875 default_value: DateTime,
876}
877
878impl RestorableDateTime {
879 pub fn new(app: &mut App, default_value: DateTime) -> Ref<RestorableDateTime> {
884 app.create(RestorableDateTime {
885 change_notifier: ChangeNotifierData::new(),
886 property: RestorablePropertyData::new(),
887 value: RestorableValueData::new(),
888 default_value,
889 })
890 }
891}
892
893impl ChangeNotifier for RestorableDateTime {
894 fn change_notifier_data(&self) -> &ChangeNotifierData {
895 &self.change_notifier
896 }
897
898 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
899 &mut self.change_notifier
900 }
901}
902
903impl RestorableProperty for RestorableDateTime {
904 type Value = DateTime;
905 crate::restorable_property_accessors!();
906
907 fn create_default_value(self: Handle<Self>, app: &mut App) -> DateTime {
908 app.get(self).default_value
909 }
910
911 fn from_primitives(self: Handle<Self>, _app: &mut App, data: &RestorationData) -> DateTime {
912 DateTime::from_milliseconds_since_epoch(
913 data.as_int()
914 .expect("the restoration data of a DateTime property is an int"),
915 false,
916 )
917 }
918
919 fn init_with_value(self: Handle<Self>, app: &mut App, value: DateTime) {
920 RestorableValue::init_with_value(self, app, value);
921 }
922
923 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
924 RestorationData::Int(RestorableValue::value(self, app).milliseconds_since_epoch())
925 }
926}
927
928impl RestorableValue for RestorableDateTime {
929 crate::restorable_value_accessors!();
930
931 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<DateTime>) {
932 let _ = old_value;
933 self.notify_listeners(app);
934 }
935}
936
937pub struct RestorableDateTimeN {
946 change_notifier: ChangeNotifierData,
947 property: RestorablePropertyData,
948 value: RestorableValueData<Option<DateTime>>,
949 default_value: Option<DateTime>,
950}
951
952impl RestorableDateTimeN {
953 pub fn new(app: &mut App, default_value: Option<DateTime>) -> Ref<RestorableDateTimeN> {
958 app.create(RestorableDateTimeN {
959 change_notifier: ChangeNotifierData::new(),
960 property: RestorablePropertyData::new(),
961 value: RestorableValueData::new(),
962 default_value,
963 })
964 }
965}
966
967impl ChangeNotifier for RestorableDateTimeN {
968 fn change_notifier_data(&self) -> &ChangeNotifierData {
969 &self.change_notifier
970 }
971
972 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
973 &mut self.change_notifier
974 }
975}
976
977impl RestorableProperty for RestorableDateTimeN {
978 type Value = Option<DateTime>;
979 crate::restorable_property_accessors!();
980
981 fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<DateTime> {
982 app.get(self).default_value
983 }
984
985 fn from_primitives(
986 self: Handle<Self>,
987 _app: &mut App,
988 data: &RestorationData,
989 ) -> Option<DateTime> {
990 data.as_int()
991 .map(|milliseconds| DateTime::from_milliseconds_since_epoch(milliseconds, false))
992 }
993
994 fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<DateTime>) {
995 RestorableValue::init_with_value(self, app, value);
996 }
997
998 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
999 RestorableValue::value(self, app).map_or(RestorationData::Null, |value| {
1000 RestorationData::Int(value.milliseconds_since_epoch())
1001 })
1002 }
1003}
1004
1005impl RestorableValue for RestorableDateTimeN {
1006 crate::restorable_value_accessors!();
1007
1008 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<DateTime>>) {
1009 let _ = old_value;
1010 self.notify_listeners(app);
1011 }
1012}
1013
1014fn enum_name<T: Debug>(value: &T) -> String {
1019 format!("{value:?}")
1020}
1021
1022pub struct RestorableEnum<T: Copy + Debug + PartialEq + 'static> {
1040 change_notifier: ChangeNotifierData,
1041 property: RestorablePropertyData,
1042 value: RestorableValueData<T>,
1043 default_value: T,
1044 values: Vec<T>,
1045}
1046
1047impl<T: Copy + Debug + PartialEq + 'static> RestorableEnum<T> {
1048 pub fn new(
1053 app: &mut App,
1054 default_value: T,
1055 values: impl IntoIterator<Item = T>,
1056 ) -> Ref<RestorableEnum<T>> {
1057 let values: Vec<T> = values.into_iter().collect();
1058 assert!(
1059 values.contains(&default_value),
1060 "Default value {default_value:?} not found in the values: {values:?}"
1061 );
1062 app.create(RestorableEnum {
1063 change_notifier: ChangeNotifierData::new(),
1064 property: RestorablePropertyData::new(),
1065 value: RestorableValueData::new(),
1066 default_value,
1067 values,
1068 })
1069 }
1070
1071 pub fn values(self: Handle<Self>, app: &App) -> &[T] {
1079 &app.get(self).values
1080 }
1081
1082 pub fn set_values(self: Handle<Self>, app: &mut App, values: impl IntoIterator<Item = T>) {
1084 app.get_mut(self).values = values.into_iter().collect();
1085 }
1086}
1087
1088impl<T: Copy + Debug + PartialEq + 'static> ChangeNotifier for RestorableEnum<T> {
1089 fn change_notifier_data(&self) -> &ChangeNotifierData {
1090 &self.change_notifier
1091 }
1092
1093 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1094 &mut self.change_notifier
1095 }
1096}
1097
1098impl<T: Copy + Debug + PartialEq + 'static> RestorableProperty for RestorableEnum<T> {
1099 type Value = T;
1100 crate::restorable_property_accessors!();
1101
1102 fn create_default_value(self: Handle<Self>, app: &mut App) -> T {
1103 app.get(self).default_value
1104 }
1105
1106 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> T {
1107 if let Some(name) = data.as_str() {
1108 if let Some(allowed) = app
1109 .get(self)
1110 .values
1111 .iter()
1112 .find(|value| enum_name(value) == name)
1113 {
1114 return *allowed;
1115 }
1116 debug_assert!(
1117 false,
1118 "Attempted to restore an unknown enum value \"{name}\" that is not in the valid \
1119 set of enum values: {:?}",
1120 app.get(self).values
1121 );
1122 }
1123 app.get(self).default_value
1124 }
1125
1126 fn init_with_value(self: Handle<Self>, app: &mut App, value: T) {
1127 RestorableValue::init_with_value(self, app, value);
1128 }
1129
1130 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1131 RestorationData::String(enum_name(RestorableValue::value(self, app)))
1132 }
1133}
1134
1135impl<T: Copy + Debug + PartialEq + 'static> RestorableValue for RestorableEnum<T> {
1136 crate::restorable_value_accessors!();
1137
1138 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<T>) {
1139 let _ = old_value;
1140 self.notify_listeners(app);
1141 }
1142
1143 fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &T) -> bool {
1144 assert!(
1145 app.get(self).values.contains(new_value),
1146 "Attempted to set an unknown enum value \"{new_value:?}\" that is not in the valid \
1147 set of enum values: {:?}",
1148 app.get(self).values
1149 );
1150 true
1151 }
1152}
1153
1154pub struct RestorableEnumN<T: Copy + Debug + PartialEq + 'static> {
1173 change_notifier: ChangeNotifierData,
1174 property: RestorablePropertyData,
1175 value: RestorableValueData<Option<T>>,
1176 default_value: Option<T>,
1177 values: Vec<T>,
1178}
1179
1180impl<T: Copy + Debug + PartialEq + 'static> RestorableEnumN<T> {
1181 pub fn new(
1186 app: &mut App,
1187 default_value: Option<T>,
1188 values: impl IntoIterator<Item = T>,
1189 ) -> Ref<RestorableEnumN<T>> {
1190 let values: Vec<T> = values.into_iter().collect();
1191 assert!(
1192 default_value.is_none_or(|default| values.contains(&default)),
1193 "Default value {default_value:?} not found in the values: {values:?}"
1194 );
1195 app.create(RestorableEnumN {
1196 change_notifier: ChangeNotifierData::new(),
1197 property: RestorablePropertyData::new(),
1198 value: RestorableValueData::new(),
1199 default_value,
1200 values,
1201 })
1202 }
1203
1204 pub fn values(self: Handle<Self>, app: &App) -> &[T] {
1212 &app.get(self).values
1213 }
1214
1215 pub fn set_values(self: Handle<Self>, app: &mut App, values: impl IntoIterator<Item = T>) {
1217 app.get_mut(self).values = values.into_iter().collect();
1218 }
1219}
1220
1221impl<T: Copy + Debug + PartialEq + 'static> ChangeNotifier for RestorableEnumN<T> {
1222 fn change_notifier_data(&self) -> &ChangeNotifierData {
1223 &self.change_notifier
1224 }
1225
1226 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1227 &mut self.change_notifier
1228 }
1229}
1230
1231impl<T: Copy + Debug + PartialEq + 'static> RestorableProperty for RestorableEnumN<T> {
1232 type Value = Option<T>;
1233 crate::restorable_property_accessors!();
1234
1235 fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<T> {
1236 app.get(self).default_value
1237 }
1238
1239 fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<T> {
1240 if data.is_null() {
1241 return None;
1242 }
1243 if let Some(name) = data.as_str() {
1244 if let Some(allowed) = app
1245 .get(self)
1246 .values
1247 .iter()
1248 .find(|value| enum_name(value) == name)
1249 {
1250 return Some(*allowed);
1251 }
1252 debug_assert!(
1253 false,
1254 "Attempted to set an unknown enum value \"{name}\" that is not null, or in the \
1255 valid set of enum values: {:?}",
1256 app.get(self).values
1257 );
1258 }
1259 app.get(self).default_value
1260 }
1261
1262 fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<T>) {
1263 RestorableValue::init_with_value(self, app, value);
1264 }
1265
1266 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1267 RestorableValue::value(self, app)
1268 .as_ref()
1269 .map_or(RestorationData::Null, |value| {
1270 RestorationData::String(enum_name(value))
1271 })
1272 }
1273}
1274
1275impl<T: Copy + Debug + PartialEq + 'static> RestorableValue for RestorableEnumN<T> {
1276 crate::restorable_value_accessors!();
1277
1278 fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<T>>) {
1279 let _ = old_value;
1280 self.notify_listeners(app);
1281 }
1282
1283 fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &Option<T>) -> bool {
1284 assert!(
1285 new_value.is_none_or(|value| app.get(self).values.contains(&value)),
1286 "Attempted to set an unknown enum value \"{new_value:?}\" that is not null, or in \
1287 the valid set of enum values: {:?}",
1288 app.get(self).values
1289 );
1290 true
1291 }
1292}
1293
1294pub struct RestorableListenableData<T> {
1300 value: Option<T>,
1301}
1302
1303impl<T> RestorableListenableData<T> {
1304 pub fn new() -> RestorableListenableData<T> {
1306 RestorableListenableData { value: None }
1307 }
1308}
1309
1310impl<T> Default for RestorableListenableData<T> {
1311 fn default() -> RestorableListenableData<T> {
1312 RestorableListenableData::new()
1313 }
1314}
1315
1316#[macro_export]
1319macro_rules! restorable_listenable_accessors {
1320 () => {
1321 fn restorable_listenable_data(
1322 self: ::waft_foundation::Handle<Self>,
1323 app: &::waft_foundation::App,
1324 ) -> &$crate::RestorableListenableData<Self::Value> {
1325 &app.get(self).listenable
1326 }
1327
1328 fn restorable_listenable_data_mut(
1329 self: ::waft_foundation::Handle<Self>,
1330 app: &mut ::waft_foundation::App,
1331 ) -> &mut $crate::RestorableListenableData<Self::Value> {
1332 &mut app.get_mut(self).listenable
1333 }
1334 };
1335}
1336
1337pub trait RestorableListenable: RestorableProperty<Value: Listenable + Clone + 'static> {
1349 fn restorable_listenable_data(
1352 self: Handle<Self>,
1353 app: &App,
1354 ) -> &RestorableListenableData<Self::Value>;
1355
1356 fn restorable_listenable_data_mut(
1358 self: Handle<Self>,
1359 app: &mut App,
1360 ) -> &mut RestorableListenableData<Self::Value>;
1361
1362 fn value(self: Handle<Self>, app: &App) -> Self::Value {
1372 debug_assert!(RestorableProperty::is_registered(self, app));
1373 self.restorable_listenable_data(app)
1374 .value
1375 .clone()
1376 .expect("init_with_value runs at registration")
1377 }
1378
1379 fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
1382 let listener = self.notification_listener();
1383 if let Some(old_value) = self.restorable_listenable_data(app).value.clone() {
1384 old_value.remove_listener(app, &listener);
1385 }
1386 self.restorable_listenable_data_mut(app).value = Some(value.clone());
1387 value.add_listener(app, listener);
1388 }
1389
1390 fn dispose(self: Handle<Self>, app: &mut App) {
1392 RestorableProperty::dispose_property(self, app);
1393 let listener = self.notification_listener();
1394 if let Some(value) = self.restorable_listenable_data(app).value.clone() {
1395 value.remove_listener(app, &listener);
1396 }
1397 }
1398
1399 fn notification_listener(self: Handle<Self>) -> Listener {
1401 Listener::handle_method(self, Self::forward_notification)
1402 }
1403
1404 fn forward_notification(self: Handle<Self>, app: &mut App) {
1406 self.notify_listeners(app);
1407 }
1408}
1409
1410pub trait RestorableChangeNotifier: RestorableListenable {
1425 fn dispose_value(self: Handle<Self>, app: &mut App, value: Self::Value);
1427
1428 fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
1430 self.dispose_old_value(app);
1431 RestorableListenable::init_with_value(self, app, value);
1432 }
1433
1434 fn dispose(self: Handle<Self>, app: &mut App) {
1436 self.dispose_old_value(app);
1437 RestorableListenable::dispose(self, app);
1438 }
1439
1440 fn dispose_old_value(self: Handle<Self>, app: &mut App) {
1442 if let Some(value) = self.restorable_listenable_data(app).value.clone() {
1443 app.schedule_microtask(Listener::new(move |app| {
1446 Self::dispose_value(self, app, value.clone());
1447 }));
1448 }
1449 }
1450}
1451
1452pub struct RestorableTextEditingController {
1460 change_notifier: ChangeNotifierData,
1461 property: RestorablePropertyData,
1462 listenable: RestorableListenableData<Ref<TextEditingController>>,
1463 initial_value: TextEditingValue,
1464}
1465
1466impl RestorableTextEditingController {
1467 pub fn new(app: &mut App) -> Ref<RestorableTextEditingController> {
1471 Self::from_value(app, TextEditingValue::EMPTY)
1472 }
1473
1474 pub fn text(app: &mut App, text: impl Into<String>) -> Ref<RestorableTextEditingController> {
1476 Self::from_value(app, TextEditingValue::new().text(text))
1477 }
1478
1479 pub fn from_value(
1481 app: &mut App,
1482 value: TextEditingValue,
1483 ) -> Ref<RestorableTextEditingController> {
1484 app.create(RestorableTextEditingController {
1485 change_notifier: ChangeNotifierData::new(),
1486 property: RestorablePropertyData::new(),
1487 listenable: RestorableListenableData::new(),
1488 initial_value: value,
1489 })
1490 }
1491}
1492
1493impl ChangeNotifier for RestorableTextEditingController {
1494 fn change_notifier_data(&self) -> &ChangeNotifierData {
1495 &self.change_notifier
1496 }
1497
1498 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1499 &mut self.change_notifier
1500 }
1501}
1502
1503impl RestorableProperty for RestorableTextEditingController {
1504 type Value = Ref<TextEditingController>;
1505 crate::restorable_property_accessors!();
1506
1507 fn create_default_value(self: Handle<Self>, app: &mut App) -> Ref<TextEditingController> {
1508 let initial_value = app.get(self).initial_value.clone();
1509 TextEditingController::from_value(app, Some(initial_value))
1510 }
1511
1512 fn from_primitives(
1513 self: Handle<Self>,
1514 app: &mut App,
1515 data: &RestorationData,
1516 ) -> Ref<TextEditingController> {
1517 TextEditingController::new(app).text(
1518 app,
1519 data.as_str()
1520 .expect("RestorableTextEditingController stores a String"),
1521 )
1522 }
1523
1524 fn init_with_value(self: Handle<Self>, app: &mut App, value: Ref<TextEditingController>) {
1525 RestorableChangeNotifier::init_with_value(self, app, value);
1526 }
1527
1528 fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1529 RestorationData::String(
1530 RestorableListenable::value(self, app)
1531 .text_value(app)
1532 .to_string(),
1533 )
1534 }
1535
1536 fn dispose(self: Handle<Self>, app: &mut App) {
1537 RestorableChangeNotifier::dispose(self, app);
1538 }
1539}
1540
1541impl RestorableListenable for RestorableTextEditingController {
1542 crate::restorable_listenable_accessors!();
1543}
1544
1545impl RestorableChangeNotifier for RestorableTextEditingController {
1546 fn dispose_value(self: Handle<Self>, app: &mut App, value: Ref<TextEditingController>) {
1547 value.dispose(app);
1548 }
1549}
1550
1551#[cfg(test)]
1552mod tests {
1553 use std::rc::Rc;
1554 use waft_foundation::AppCell;
1555
1556 use waft_foundation::{Handle, OptionRetained};
1557 use waft_services::{RestorationBucket, RestorationManager, RestorationMap};
1558
1559 use super::*;
1560 use crate::framework::{BuildContext, GlobalKey, KeyRef, StateData, StatefulWidget, WidgetRef};
1561 use crate::test_harness::Harness;
1562 use crate::widgets::basic::SizedBox;
1563 use crate::widgets::restoration::{
1564 RestorationMixin, RestorationMixinData, RootRestorationScope,
1565 };
1566 use crate::{IntoWidget, State};
1567
1568 #[derive(Clone, Copy, Debug, PartialEq)]
1569 enum Direction {
1570 Up,
1571 Down,
1572 }
1573
1574 const DIRECTIONS: [Direction; 2] = [Direction::Up, Direction::Down];
1575
1576 fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1577 entries
1578 .into_iter()
1579 .map(|(key, value)| (RestorationData::from(key), value))
1580 .collect()
1581 }
1582
1583 fn values<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1585 map([("v", map(entries).into())])
1586 }
1587
1588 fn child(restoration_id: &str, data: RestorationMap) -> RestorationMap {
1590 map([("c", map([(restoration_id, data.into())]).into())])
1591 }
1592
1593 #[derive(Clone)]
1595 struct Properties {
1596 int: Ref<RestorableInt>,
1597 double: Ref<RestorableDouble>,
1598 string: Ref<RestorableString>,
1599 boolean: Ref<RestorableBool>,
1600 int_n: Ref<RestorableIntN>,
1601 double_n: Ref<RestorableDoubleN>,
1602 string_n: Ref<RestorableStringN>,
1603 bool_n: Ref<RestorableBoolN>,
1604 date_time: Ref<RestorableDateTime>,
1605 date_time_n: Ref<RestorableDateTimeN>,
1606 direction: Ref<RestorableEnum<Direction>>,
1607 direction_n: Ref<RestorableEnumN<Direction>>,
1608 }
1609
1610 impl Properties {
1611 fn new(app: &mut App) -> Properties {
1612 Properties {
1613 int: RestorableInt::new(app, 1),
1614 double: RestorableDouble::new(app, 1.5),
1615 string: RestorableString::new(app, "one"),
1616 boolean: RestorableBool::new(app, true),
1617 int_n: RestorableIntN::new(app, Some(2)),
1618 double_n: RestorableDoubleN::new(app, None),
1619 string_n: RestorableStringN::new(app, None),
1620 bool_n: RestorableBoolN::new(app, Some(false)),
1621 date_time: RestorableDateTime::new(
1622 app,
1623 DateTime::from_milliseconds_since_epoch(1000, false),
1624 ),
1625 date_time_n: RestorableDateTimeN::new(app, None),
1626 direction: RestorableEnum::new(app, Direction::Up, DIRECTIONS),
1627 direction_n: RestorableEnumN::new(app, None, DIRECTIONS),
1628 }
1629 }
1630
1631 fn register(self, state: Handle<BagState>, app: &mut App) {
1632 state.register_for_restoration(app, self.int.as_property(), "int");
1633 state.register_for_restoration(app, self.double.as_property(), "double");
1634 state.register_for_restoration(app, self.string.as_property(), "string");
1635 state.register_for_restoration(app, self.boolean.as_property(), "bool");
1636 state.register_for_restoration(app, self.int_n.as_property(), "int-n");
1637 state.register_for_restoration(app, self.double_n.as_property(), "double-n");
1638 state.register_for_restoration(app, self.string_n.as_property(), "string-n");
1639 state.register_for_restoration(app, self.bool_n.as_property(), "bool-n");
1640 state.register_for_restoration(app, self.date_time.as_property(), "date-time");
1641 state.register_for_restoration(app, self.date_time_n.as_property(), "date-time-n");
1642 state.register_for_restoration(app, self.direction.as_property(), "direction");
1643 state.register_for_restoration(app, self.direction_n.as_property(), "direction-n");
1644 }
1645 }
1646
1647 #[derive(Debug)]
1648 struct Bag {
1649 key: Option<KeyRef>,
1650 }
1651
1652 impl StatefulWidget for Bag {
1653 type State = BagState;
1654
1655 fn key(&self) -> Option<&KeyRef> {
1656 self.key.as_ref()
1657 }
1658
1659 fn create_state(&self) -> BagState {
1660 BagState {
1661 state: StateData::new(),
1662 restoration: RestorationMixinData::new(),
1663 properties: None,
1664 }
1665 }
1666 }
1667
1668 struct BagState {
1669 state: StateData<Bag>,
1670 restoration: RestorationMixinData,
1671 properties: Option<Properties>,
1672 }
1673
1674 impl RestorationMixin for BagState {
1675 crate::restoration_mixin_accessors!();
1676
1677 fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
1678 Some("bag")
1679 }
1680
1681 fn restore_state(
1682 self: Handle<Self>,
1683 app: &mut App,
1684 _old_bucket: Option<Handle<RestorationBucket>>,
1685 _initial_restore: bool,
1686 ) {
1687 let properties = match app.get(self).properties.clone() {
1688 Some(properties) => properties,
1689 None => {
1690 let properties = Properties::new(app);
1691 app.get_mut(self).properties = Some(properties.clone());
1692 properties
1693 }
1694 };
1695 properties.register(self, app);
1696 }
1697 }
1698
1699 impl State for BagState {
1700 type Widget = Bag;
1701 crate::state_accessors!();
1702
1703 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1704 self.did_change_dependencies_restoration(app);
1705 }
1706
1707 fn dispose(self: Handle<Self>, app: &mut App) {
1708 self.dispose_restoration(app);
1709 }
1710
1711 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1712 let _ = app;
1713 SizedBox::shrink().into_widget()
1714 }
1715 }
1716
1717 struct Fixture {
1719 cell: Rc<AppCell>,
1720 properties: Properties,
1721 bucket: Handle<RestorationBucket>,
1722 }
1723
1724 impl Fixture {
1725 fn mount(data: Option<RestorationMap>) -> Fixture {
1726 let cell = AppCell::new();
1727 let mut app = cell.borrow_mut();
1728 let manager = RestorationManager::instance(&mut app);
1729 manager.handle_restoration_update_from_engine(&mut app, true, data);
1730 let key = GlobalKey::new();
1731 let harness = Harness::mount(
1732 &mut app,
1733 RootRestorationScope::new(
1734 Some("app".to_string()),
1735 Bag {
1736 key: Some(key.clone().into()),
1737 },
1738 )
1739 .into_widget(),
1740 );
1741 harness.pump(&mut app);
1742 let state = harness
1743 .owner
1744 .global_key_element(&app, &key)
1745 .expect("the bag is in the tree")
1746 .state_handle::<BagState>(&app)
1747 .expect("a BagState");
1748 let properties = app
1749 .get(state)
1750 .properties
1751 .clone()
1752 .expect("restore_state ran");
1753 let bucket = state.bucket(&app).expect("the bag claimed a bucket");
1754 drop(app);
1755 Fixture {
1756 cell,
1757 properties,
1758 bucket,
1759 }
1760 }
1761
1762 fn stored(&mut self, restoration_id: &str) -> Option<RestorationData> {
1763 self.bucket
1764 .read(&mut self.cell.borrow_mut(), restoration_id)
1765 }
1766 }
1767
1768 fn filled() -> Option<RestorationMap> {
1770 Some(child(
1771 "app",
1772 child(
1773 "bag",
1774 values([
1775 ("int", 7i64.into()),
1776 ("double", 2.5f64.into()),
1777 ("string", "seven".into()),
1778 ("bool", false.into()),
1779 ("int-n", RestorationData::Null),
1780 ("double-n", 0.5f64.into()),
1781 ("string-n", "maybe".into()),
1782 ("bool-n", RestorationData::Null),
1783 ("date-time", 2000i64.into()),
1784 ("date-time-n", 3000i64.into()),
1785 ("direction", "Down".into()),
1786 ("direction-n", "Up".into()),
1787 ]),
1788 ),
1789 ))
1790 }
1791
1792 #[test]
1793 fn a_property_with_no_stored_value_takes_the_default_it_was_created_with() {
1794 let fixture = Fixture::mount(None);
1795 let properties = fixture.properties.clone();
1796 let app = &mut fixture.cell.borrow_mut();
1797
1798 assert_eq!(*properties.int.value(app), 1);
1799 assert_eq!(*properties.double.value(app), 1.5);
1800 assert_eq!(properties.string.value(app), "one");
1801 assert!(*properties.boolean.value(app));
1802 assert_eq!(*properties.int_n.value(app), Some(2));
1803 assert_eq!(*properties.double_n.value(app), None);
1804 assert_eq!(*properties.string_n.value(app), None);
1805 assert_eq!(*properties.bool_n.value(app), Some(false));
1806 assert_eq!(
1807 *properties.date_time.value(app),
1808 DateTime::from_milliseconds_since_epoch(1000, false)
1809 );
1810 assert_eq!(*properties.date_time_n.value(app), None);
1811 assert_eq!(*properties.direction.value(app), Direction::Up);
1812 assert_eq!(*properties.direction_n.value(app), None);
1813 }
1814
1815 #[test]
1816 fn a_default_value_is_written_into_the_bucket_at_registration() {
1817 let mut fixture = Fixture::mount(None);
1818
1819 assert_eq!(fixture.stored("int"), Some(1i64.into()));
1820 assert_eq!(fixture.stored("double"), Some(1.5f64.into()));
1821 assert_eq!(fixture.stored("string"), Some("one".into()));
1822 assert_eq!(fixture.stored("bool"), Some(true.into()));
1823 assert_eq!(fixture.stored("int-n"), Some(2i64.into()));
1824 assert_eq!(fixture.stored("double-n"), Some(RestorationData::Null));
1825 assert_eq!(fixture.stored("string-n"), Some(RestorationData::Null));
1826 assert_eq!(fixture.stored("bool-n"), Some(false.into()));
1827 assert_eq!(fixture.stored("date-time"), Some(1000i64.into()));
1828 assert_eq!(fixture.stored("date-time-n"), Some(RestorationData::Null));
1829 assert_eq!(fixture.stored("direction"), Some("Up".into()));
1830 assert_eq!(fixture.stored("direction-n"), Some(RestorationData::Null));
1831 }
1832
1833 #[test]
1834 fn every_property_restores_the_value_the_data_describes() {
1835 let fixture = Fixture::mount(filled());
1836 let properties = fixture.properties.clone();
1837 let app = &mut fixture.cell.borrow_mut();
1838
1839 assert_eq!(*properties.int.value(app), 7);
1840 assert_eq!(*properties.double.value(app), 2.5);
1841 assert_eq!(properties.string.value(app), "seven");
1842 assert!(!*properties.boolean.value(app));
1843 assert_eq!(*properties.int_n.value(app), None);
1844 assert_eq!(*properties.double_n.value(app), Some(0.5));
1845 assert_eq!(properties.string_n.value(app).as_deref(), Some("maybe"));
1846 assert_eq!(*properties.bool_n.value(app), None);
1847 assert_eq!(
1848 *properties.date_time.value(app),
1849 DateTime::from_milliseconds_since_epoch(2000, false)
1850 );
1851 assert_eq!(
1852 *properties.date_time_n.value(app),
1853 Some(DateTime::from_milliseconds_since_epoch(3000, false))
1854 );
1855 assert_eq!(*properties.direction.value(app), Direction::Down);
1856 assert_eq!(*properties.direction_n.value(app), Some(Direction::Up));
1857 }
1858
1859 #[test]
1860 fn a_new_value_is_written_back_as_the_data_it_was_restored_from() {
1861 let mut fixture = Fixture::mount(filled());
1862 let properties = fixture.properties.clone();
1863 {
1864 let app = &mut fixture.cell.borrow_mut();
1865 properties.int.set_value(app, 8);
1866 properties.double.set_value(app, 3.5);
1867 properties.string.set_value(app, "eight".to_string());
1868 properties.boolean.set_value(app, true);
1869 properties.int_n.set_value(app, Some(9));
1870 properties.double_n.set_value(app, None);
1871 properties.string_n.set_value(app, Some("nine".to_string()));
1872 properties.bool_n.set_value(app, Some(true));
1873 let date_time = DateTime::from_milliseconds_since_epoch(4000, false);
1874 properties.date_time.set_value(app, date_time);
1875 properties.date_time_n.set_value(app, None);
1876 properties.direction.set_value(app, Direction::Up);
1877 properties.direction_n.set_value(app, Some(Direction::Down));
1878 }
1879
1880 assert_eq!(fixture.stored("int"), Some(8i64.into()));
1881 assert_eq!(fixture.stored("double"), Some(3.5f64.into()));
1882 assert_eq!(fixture.stored("string"), Some("eight".into()));
1883 assert_eq!(fixture.stored("bool"), Some(true.into()));
1884 assert_eq!(fixture.stored("int-n"), Some(9i64.into()));
1885 assert_eq!(fixture.stored("double-n"), Some(RestorationData::Null));
1886 assert_eq!(fixture.stored("string-n"), Some("nine".into()));
1887 assert_eq!(fixture.stored("bool-n"), Some(true.into()));
1888 assert_eq!(fixture.stored("date-time"), Some(4000i64.into()));
1889 assert_eq!(fixture.stored("date-time-n"), Some(RestorationData::Null));
1890 assert_eq!(fixture.stored("direction"), Some("Up".into()));
1891 assert_eq!(fixture.stored("direction-n"), Some("Down".into()));
1892 }
1893
1894 #[test]
1895 fn setting_the_value_it_already_has_writes_nothing() {
1896 let fixture = Fixture::mount(filled());
1897 let int = fixture.properties.int.clone();
1898 let notified = Rc::new(std::cell::Cell::new(0usize));
1899 let seen = Rc::clone(¬ified);
1900 int.add_listener(
1901 &mut fixture.cell.borrow_mut(),
1902 Listener::new(move |_app| seen.set(seen.get() + 1)),
1903 );
1904
1905 int.set_value(&mut fixture.cell.borrow_mut(), 7);
1906 assert_eq!(notified.get(), 0, "the value did not change");
1907
1908 int.set_value(&mut fixture.cell.borrow_mut(), 8);
1909 assert_eq!(notified.get(), 1);
1910 }
1911
1912 #[test]
1913 fn an_unregistered_property_is_removed_from_the_data() {
1914 let mut fixture = Fixture::mount(filled());
1915 let int = fixture.properties.int.clone();
1916 let state = int.state(&fixture.cell.borrow());
1917 let bag = state
1918 .downcast::<BagState>(&fixture.cell.borrow())
1919 .expect("the owner is the bag");
1920 bag.unregister_from_restoration(&mut fixture.cell.borrow_mut(), int.as_property());
1921
1922 assert_eq!(fixture.stored("int"), None);
1923 assert!(!int.as_property().is_registered(&fixture.cell.borrow()));
1924 }
1925
1926 #[test]
1927 fn restorable_text_editing_controller_create_default_value_holds_initial_text() {
1928 let cell = AppCell::new();
1929 let mut app = cell.borrow_mut();
1930 let property = RestorableTextEditingController::from_value(
1931 &mut app,
1932 TextEditingValue::new().text("hello"),
1933 );
1934 let controller = RestorableProperty::create_default_value(property.handle(), &mut app);
1935 assert_eq!(controller.text_value(&app), "hello");
1936 let restored = RestorableProperty::from_primitives(
1937 property.handle(),
1938 &mut app,
1939 &RestorationData::String("hello".into()),
1940 );
1941 assert_eq!(restored.text_value(&app), "hello");
1942 }
1943
1944 #[derive(Debug)]
1945 struct Editor {
1946 key: Option<KeyRef>,
1947 }
1948
1949 impl StatefulWidget for Editor {
1950 type State = EditorState;
1951
1952 fn key(&self) -> Option<&KeyRef> {
1953 self.key.as_ref()
1954 }
1955
1956 fn create_state(&self) -> EditorState {
1957 EditorState {
1958 state: StateData::new(),
1959 restoration: RestorationMixinData::new(),
1960 controller: None,
1961 }
1962 }
1963 }
1964
1965 struct EditorState {
1966 state: StateData<Editor>,
1967 restoration: RestorationMixinData,
1968 controller: Option<Ref<RestorableTextEditingController>>,
1969 }
1970
1971 impl RestorationMixin for EditorState {
1972 crate::restoration_mixin_accessors!();
1973
1974 fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
1975 Some("editor")
1976 }
1977
1978 fn restore_state(
1979 self: Handle<Self>,
1980 app: &mut App,
1981 _old_bucket: Option<Handle<RestorationBucket>>,
1982 _initial_restore: bool,
1983 ) {
1984 let controller = match app.get(self).controller.handle() {
1985 Some(controller) => controller,
1986 None => {
1987 let controller = RestorableTextEditingController::text(app, "hello");
1988 let handle = controller.handle();
1989 app.get_mut(self).controller = Some(controller);
1990 handle
1991 }
1992 };
1993 self.register_for_restoration(app, controller.as_property(), "controller");
1994 }
1995 }
1996
1997 impl State for EditorState {
1998 type Widget = Editor;
1999 crate::state_accessors!();
2000
2001 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2002 self.did_change_dependencies_restoration(app);
2003 }
2004
2005 fn dispose(self: Handle<Self>, app: &mut App) {
2006 self.dispose_restoration(app);
2007 }
2008
2009 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2010 let _ = app;
2011 SizedBox::shrink().into_widget()
2012 }
2013 }
2014
2015 #[test]
2016 fn restorable_text_editing_to_primitives_is_the_controller_text() {
2017 let cell = AppCell::new();
2018 let mut app = cell.borrow_mut();
2019 let manager = RestorationManager::instance(&mut app);
2020 manager.handle_restoration_update_from_engine(&mut app, true, None);
2021 let key = GlobalKey::new();
2022 let harness = Harness::mount(
2023 &mut app,
2024 RootRestorationScope::new(
2025 Some("app".to_string()),
2026 Editor {
2027 key: Some(key.clone().into()),
2028 },
2029 )
2030 .into_widget(),
2031 );
2032 harness.pump(&mut app);
2033 let state = harness
2034 .owner
2035 .global_key_element(&app, &key)
2036 .expect("the editor is in the tree")
2037 .state_handle::<EditorState>(&app)
2038 .expect("an EditorState");
2039 let controller = app
2040 .get(state)
2041 .controller
2042 .handle()
2043 .expect("restore_state ran");
2044 assert_eq!(
2045 RestorableListenable::value(controller, &app).text_value(&app),
2046 "hello"
2047 );
2048 assert_eq!(
2049 RestorableProperty::to_primitives(controller, &app),
2050 RestorationData::String("hello".into())
2051 );
2052 }
2053}