1use std::any::TypeId;
4use std::cell::Cell;
5use std::collections::HashMap;
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_embedder::TargetPlatform;
11use waft_foundation::{
12 App, ChangeNotifier, ChangeNotifierData, Handle, Listener, OptionRetained, Timer,
13 ValueListenable, ValueNotifier, describe_identity,
14};
15use waft_services::{UndoDirection, UndoManager, UndoManagerClient};
16
17use crate::framework::{
18 BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
19};
20use crate::widgets::actions::{Actions, AnyAction, CallbackAction};
21use crate::widgets::focus_manager::FocusNodeRef;
22use crate::widgets::text_editing_intents::{RedoTextIntent, UndoTextIntent};
23use waft_foundation::ListenableObject;
24use waft_foundation::Ref;
25
26pub type UndoHistoryOnTriggered<T> = Rc<dyn Fn(&mut App, T)>;
28
29pub type ShouldChangeUndoStack<T> = Rc<dyn Fn(Option<&T>, &T) -> bool>;
31
32pub type UndoStackModifier<T> = Rc<dyn Fn(T) -> T>;
34
35pub struct UndoHistory<
51 T: Clone + PartialEq + 'static,
52 V: ValueListenable<T> + Clone + PartialEq + 'static = Ref<ValueNotifier<T>>,
53> {
54 pub key: Option<KeyRef>,
56 pub should_change_undo_stack: Option<ShouldChangeUndoStack<T>>,
59 pub value: V,
61 pub on_triggered: UndoHistoryOnTriggered<T>,
72 pub focus_node: FocusNodeRef,
75 pub undo_stack_modifier: Option<UndoStackModifier<T>>,
82 pub controller: Option<Ref<UndoHistoryController>>,
86 pub child: WidgetRef,
88}
89
90impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
91 UndoHistory<T, V>
92{
93 #[cfg_attr(debug_assertions, track_caller)]
95 pub fn new<K>(
96 value: V,
97 on_triggered: impl Fn(&mut App, T) + 'static,
98 focus_node: FocusNodeRef,
99 child: impl IntoWidget<K>,
100 ) -> UndoHistory<T, V> {
101 UndoHistory {
102 key: None,
103 should_change_undo_stack: None,
104 value,
105 on_triggered: Rc::new(on_triggered),
106 focus_node,
107 undo_stack_modifier: None,
108 controller: None,
109 child: child.into_widget(),
110 }
111 }
112
113 pub fn key(mut self, key: KeyRef) -> UndoHistory<T, V> {
115 self.key = Some(key);
116 self
117 }
118
119 pub fn should_change_undo_stack(
121 mut self,
122 should_change_undo_stack: impl Fn(Option<&T>, &T) -> bool + 'static,
123 ) -> UndoHistory<T, V> {
124 self.should_change_undo_stack = Some(Rc::new(should_change_undo_stack));
125 self
126 }
127
128 pub fn undo_stack_modifier(
130 mut self,
131 undo_stack_modifier: impl Fn(T) -> T + 'static,
132 ) -> UndoHistory<T, V> {
133 self.undo_stack_modifier = Some(Rc::new(undo_stack_modifier));
134 self
135 }
136
137 pub fn controller(mut self, controller: Ref<UndoHistoryController>) -> UndoHistory<T, V> {
139 self.controller = Some(controller);
140 self
141 }
142}
143
144impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static> Debug
145 for UndoHistory<T, V>
146{
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 f.debug_struct("UndoHistory")
149 .field("child", &self.child)
150 .finish_non_exhaustive()
151 }
152}
153
154impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
155 StatefulWidget for UndoHistory<T, V>
156{
157 type State = UndoHistoryState<T, V>;
158
159 fn key(&self) -> Option<&KeyRef> {
160 self.key.as_ref()
161 }
162
163 fn create_state(&self) -> UndoHistoryState<T, V> {
164 UndoHistoryState {
165 state: StateData::new(),
166 stack: UndoStack::new(),
167 throttle_timer: None,
168 throttle_arg: None,
169 during_trigger: Rc::new(Cell::new(false)),
170 last_value: None,
171 controller: None,
172 }
173 }
174}
175
176pub struct UndoHistoryState<
182 T: Clone + PartialEq + 'static,
183 V: ValueListenable<T> + Clone + PartialEq + 'static = Ref<ValueNotifier<T>>,
184> {
185 state: StateData<UndoHistory<T, V>>,
186 stack: UndoStack<T>,
187 throttle_timer: Option<Timer>,
188 throttle_arg: Option<T>,
189 during_trigger: Rc<Cell<bool>>,
190 last_value: Option<T>,
194 controller: Option<Ref<UndoHistoryController>>,
195}
196
197struct DuringTriggerGuard {
200 flag: Rc<Cell<bool>>,
201}
202
203impl DuringTriggerGuard {
204 fn enter(flag: &Rc<Cell<bool>>) -> DuringTriggerGuard {
205 flag.set(true);
206 DuringTriggerGuard {
207 flag: Rc::clone(flag),
208 }
209 }
210}
211
212impl Drop for DuringTriggerGuard {
213 fn drop(&mut self) {
214 self.flag.set(false);
215 }
216}
217
218impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
219 UndoHistoryState<T, V>
220{
221 fn effective_controller(self: Handle<Self>, app: &mut App) -> Handle<UndoHistoryController> {
222 if let Some(controller) = self.widget(app).controller.handle() {
223 return controller;
224 }
225 if let Some(controller) = app.get(self).controller.handle() {
226 return controller;
227 }
228 let controller = UndoHistoryController::new(app);
229 let handle = controller.handle();
230 app.get_mut(self).controller = Some(controller);
231 handle
232 }
233
234 pub fn undo(self: Handle<Self>, app: &mut App) {
236 if app.get(self).stack.current_value().is_none() {
237 return;
242 }
243 if app
244 .get(self)
245 .throttle_timer
246 .is_some_and(|timer| timer.is_active(app))
247 {
248 if let Some(timer) = app.get(self).throttle_timer {
249 timer.cancel(app); }
251 let next = app.get(self).stack.current_value().cloned();
252 self.update(app, next);
253 } else {
254 let next = app.get_mut(self).stack.undo().cloned();
255 self.update(app, next);
256 }
257 self.update_state(app);
258 }
259
260 pub fn redo(self: Handle<Self>, app: &mut App) {
262 let next = app.get_mut(self).stack.redo().cloned();
263 self.update(app, next);
264 self.update_state(app);
265 }
266
267 pub fn can_undo(self: Handle<Self>, app: &App) -> bool {
269 app.get(self).stack.can_undo()
270 }
271
272 pub fn can_redo(self: Handle<Self>, app: &App) -> bool {
274 app.get(self).stack.can_redo()
275 }
276
277 fn update_state(self: Handle<Self>, app: &mut App) {
278 let can_undo = self.can_undo(app);
279 let can_redo = self.can_redo(app);
280 let controller = self.effective_controller(app);
281 controller.set_value(
282 app,
283 UndoHistoryValue::new()
284 .can_undo(can_undo)
285 .can_redo(can_redo),
286 );
287
288 if app.platform().target_platform() != TargetPlatform::IOS {
289 return;
290 }
291
292 if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
293 UndoManager::set_undo_state(app, can_undo, can_redo);
294 }
295 }
296
297 fn undo_from_intent(self: Handle<Self>, app: &mut App) {
298 self.undo(app);
299 }
300
301 fn redo_from_intent(self: Handle<Self>, app: &mut App) {
302 self.redo(app);
303 }
304
305 fn update(self: Handle<Self>, app: &mut App, next_value: Option<T>) {
306 let Some(next_value) = next_value else {
307 return;
308 };
309 if app.get(self).last_value.as_ref() == Some(&next_value) {
310 return;
311 }
312 app.get_mut(self).last_value = Some(next_value.clone());
313 let flag = Rc::clone(&app.get(self).during_trigger);
314 let _guard = DuringTriggerGuard::enter(&flag);
315 let on_triggered = Rc::clone(&self.widget(app).on_triggered);
316 on_triggered(app, next_value.clone());
317 debug_assert!(self.widget(app).value.value(app) == &next_value);
318 }
319
320 fn push(self: Handle<Self>, app: &mut App) {
321 let current = self.widget(app).value.value(app).clone();
322 if app.get(self).last_value.as_ref() == Some(¤t) {
323 return;
324 }
325
326 if app.get(self).during_trigger.get() {
327 return;
328 }
329
330 if let Some(should_change) = self.widget(app).should_change_undo_stack.clone()
331 && !should_change(app.get(self).last_value.as_ref(), ¤t)
332 {
333 return;
334 }
335
336 let next_value = if let Some(modifier) = self.widget(app).undo_stack_modifier.clone() {
337 modifier(current)
338 } else {
339 current
340 };
341 if app.get(self).last_value.as_ref() == Some(&next_value) {
342 return;
343 }
344
345 app.get_mut(self).last_value = Some(next_value.clone());
346
347 let timer = self.throttled_push(app, next_value);
348 app.get_mut(self).throttle_timer = Some(timer);
349 }
350
351 fn handle_focus(self: Handle<Self>, app: &mut App) {
352 let focus_node = self.widget(app).focus_node.handle();
353 if !focus_node.has_focus(app) {
354 if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
355 UndoManager::set_client(app, None);
356 }
357
358 return;
359 }
360 UndoManager::set_client(app, Some(self.as_undo_manager_client()));
361 self.update_state(app);
362 }
363
364 fn throttled_push(self: Handle<Self>, app: &mut App, current_arg: T) -> Timer {
366 app.get_mut(self).throttle_arg = Some(current_arg);
367 if let Some(timer) = app.get(self).throttle_timer
368 && timer.is_active(app)
369 {
370 return timer;
371 }
372 Timer::new(
373 app,
374 K_THROTTLE_DURATION,
375 Listener::handle_method(self, Self::throttled_push_fire),
376 )
377 }
378
379 fn throttled_push_fire(self: Handle<Self>, app: &mut App) {
380 let arg = app
381 .get_mut(self)
382 .throttle_arg
383 .take()
384 .expect("throttled push stores the arg");
385 app.get_mut(self).throttle_timer = None;
386 app.get_mut(self).stack.push(arg);
387 self.update_state(app);
388 }
389}
390
391impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
392 UndoManagerClient for UndoHistoryState<T, V>
393{
394 fn handle_platform_undo(self: Handle<Self>, app: &mut App, direction: UndoDirection) {
395 match direction {
396 UndoDirection::Undo => self.undo(app),
397 UndoDirection::Redo => self.redo(app),
398 }
399 }
400
401 fn undo(self: Handle<Self>, app: &mut App) {
402 UndoHistoryState::undo(self, app);
403 }
404
405 fn redo(self: Handle<Self>, app: &mut App) {
406 UndoHistoryState::redo(self, app);
407 }
408
409 fn can_undo(self: Handle<Self>, app: &App) -> bool {
410 UndoHistoryState::can_undo(self, app)
411 }
412
413 fn can_redo(self: Handle<Self>, app: &App) -> bool {
414 UndoHistoryState::can_redo(self, app)
415 }
416}
417
418impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static> State
419 for UndoHistoryState<T, V>
420{
421 type Widget = UndoHistory<T, V>;
422 crate::state_accessors!();
423
424 fn init_state(self: Handle<Self>, app: &mut App) {
425 self.push(app);
426 let value = self.widget(app).value.clone();
427 value.add_listener(app, Listener::handle_method(self, Self::push));
428 self.handle_focus(app);
429 let focus_node = self.widget(app).focus_node.handle();
430 focus_node.add_listener(app, Listener::handle_method(self, Self::handle_focus));
431 let controller = self.effective_controller(app);
432 controller
433 .on_undo(app)
434 .add_listener(app, Listener::handle_method(self, Self::undo));
435 let controller = self.effective_controller(app);
436 controller
437 .on_redo(app)
438 .add_listener(app, Listener::handle_method(self, Self::redo));
439 }
440
441 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &UndoHistory<T, V>) {
442 let value = self.widget(app).value.clone();
443 if value != old_widget.value {
444 app.get_mut(self).stack.clear();
445 old_widget
446 .value
447 .remove_listener(app, &Listener::handle_method(self, Self::push));
448 value.add_listener(app, Listener::handle_method(self, Self::push));
449 }
450 let focus_node = self.widget(app).focus_node.handle();
451 if focus_node != old_widget.focus_node {
452 old_widget
453 .focus_node
454 .remove_listener(app, &Listener::handle_method(self, Self::handle_focus));
455 focus_node.add_listener(app, Listener::handle_method(self, Self::handle_focus));
456 }
457 if self.widget(app).controller != old_widget.controller {
458 let controller = self.effective_controller(app);
459 controller
460 .on_undo(app)
461 .remove_listener(app, &Listener::handle_method(self, Self::undo));
462 let controller = self.effective_controller(app);
463 controller
464 .on_redo(app)
465 .remove_listener(app, &Listener::handle_method(self, Self::redo));
466 if let Some(controller) = app.get(self).controller.handle() {
467 controller.dispose(app);
468 }
469 app.get_mut(self).controller = None;
470 let controller = self.effective_controller(app);
471 controller
472 .on_undo(app)
473 .add_listener(app, Listener::handle_method(self, Self::undo));
474 let controller = self.effective_controller(app);
475 controller
476 .on_redo(app)
477 .add_listener(app, Listener::handle_method(self, Self::redo));
478 }
479 }
480
481 fn dispose(self: Handle<Self>, app: &mut App) {
482 if UndoManager::client(app) == Some(self.as_undo_manager_client()) {
483 UndoManager::set_client(app, None);
484 }
485
486 let value = self.widget(app).value.clone();
487 value.remove_listener(app, &Listener::handle_method(self, Self::push));
488 let focus_node = self.widget(app).focus_node.handle();
489 focus_node.remove_listener(app, &Listener::handle_method(self, Self::handle_focus));
490 let controller = self.effective_controller(app);
491 controller
492 .on_undo(app)
493 .remove_listener(app, &Listener::handle_method(self, Self::undo));
494 let controller = self.effective_controller(app);
495 controller
496 .on_redo(app)
497 .remove_listener(app, &Listener::handle_method(self, Self::redo));
498 if let Some(controller) = app.get(self).controller.handle() {
499 controller.dispose(app);
500 }
501 if let Some(timer) = app.get(self).throttle_timer {
502 timer.cancel(app);
503 }
504 }
505
506 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
507 let child = self.widget(app).child.clone();
508 let undo_default = CallbackAction::<UndoTextIntent>::new(
509 app,
510 Rc::new({
511 let this = self;
512 move |app, _intent| {
513 this.undo_from_intent(app);
514 None
515 }
516 }),
517 );
518 let redo_default = CallbackAction::<RedoTextIntent>::new(
519 app,
520 Rc::new({
521 let this = self;
522 move |app, _intent| {
523 this.redo_from_intent(app);
524 None
525 }
526 }),
527 );
528 let undo = AnyAction::overridable(app, undo_default.into_erased(), context);
529 let redo = AnyAction::overridable(app, redo_default.into_erased(), context);
530 Actions::new(
531 HashMap::from([
532 (TypeId::of::<UndoTextIntent>(), undo),
533 (TypeId::of::<RedoTextIntent>(), redo),
534 ]),
535 child,
536 )
537 .into_widget()
538 }
539}
540
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
543pub struct UndoHistoryValue {
544 pub can_undo: bool,
546 pub can_redo: bool,
548}
549
550impl UndoHistoryValue {
551 pub const EMPTY: UndoHistoryValue = UndoHistoryValue {
553 can_undo: false,
554 can_redo: false,
555 };
556
557 pub const fn new() -> UndoHistoryValue {
562 UndoHistoryValue::EMPTY
563 }
564
565 pub const fn can_undo(mut self, can_undo: bool) -> UndoHistoryValue {
567 self.can_undo = can_undo;
568 self
569 }
570
571 pub const fn can_redo(mut self, can_redo: bool) -> UndoHistoryValue {
573 self.can_redo = can_redo;
574 self
575 }
576}
577
578impl Default for UndoHistoryValue {
579 fn default() -> UndoHistoryValue {
580 UndoHistoryValue::EMPTY
581 }
582}
583
584impl fmt::Display for UndoHistoryValue {
585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
587 write!(
588 f,
589 "UndoHistoryValue(canUndo: {}, canRedo: {})",
590 self.can_undo, self.can_redo
591 )
592 }
593}
594
595pub struct UndoHistoryController {
611 change_notifier: ChangeNotifierData,
612 value: UndoHistoryValue,
613 on_undo: Ref<ChangeNotifierData>,
614 on_redo: Ref<ChangeNotifierData>,
615}
616
617impl Debug for UndoHistoryController {
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 f.debug_struct("UndoHistoryController")
620 .field("value", &self.value)
621 .finish()
622 }
623}
624
625impl UndoHistoryController {
626 pub fn new(app: &mut App) -> Ref<UndoHistoryController> {
628 Self::from_value(app, UndoHistoryValue::EMPTY)
629 }
630
631 pub fn from_value(app: &mut App, value: UndoHistoryValue) -> Ref<UndoHistoryController> {
633 let on_undo = app.create(ChangeNotifierData::new());
634 let on_redo = app.create(ChangeNotifierData::new());
635 app.create(UndoHistoryController {
636 change_notifier: ChangeNotifierData::new(),
637 value,
638 on_undo,
639 on_redo,
640 })
641 }
642
643 pub fn value(self: Handle<Self>, app: &App) -> &UndoHistoryValue {
645 &app.get(self).value
646 }
647
648 pub fn set_value(self: Handle<Self>, app: &mut App, new_value: UndoHistoryValue) {
650 if app.get(self).value == new_value {
651 return;
652 }
653 app.get_mut(self).value = new_value;
654 self.notify_listeners(app);
655 }
656
657 pub fn on_undo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
659 app.get(self).on_undo.handle()
660 }
661
662 pub fn on_redo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
664 app.get(self).on_redo.handle()
665 }
666
667 pub fn undo(self: Handle<Self>, app: &mut App) {
669 if !self.value(app).can_undo {
670 return;
671 }
672 let on_undo = self.on_undo(app);
673 on_undo.notify_listeners(app);
674 }
675
676 pub fn redo(self: Handle<Self>, app: &mut App) {
678 if !self.value(app).can_redo {
679 return;
680 }
681 let on_redo = self.on_redo(app);
682 on_redo.notify_listeners(app);
683 }
684
685 pub fn dispose(self: Handle<Self>, app: &mut App) {
687 let on_undo = self.on_undo(app);
688 let on_redo = self.on_redo(app);
689 ChangeNotifierData::dispose(app, on_undo);
690 ChangeNotifierData::dispose(app, on_redo);
691 ChangeNotifierData::dispose(app, self);
692 }
693}
694
695impl UndoHistoryController {
696 pub fn to_string(self: Handle<Self>, app: &App) -> String {
699 format!(
700 "{}({})",
701 describe_identity("UndoHistoryController", self.id().identity_hash()),
702 self.value(app)
703 )
704 }
705}
706
707impl ChangeNotifier for UndoHistoryController {
708 fn change_notifier_data(&self) -> &ChangeNotifierData {
709 &self.change_notifier
710 }
711
712 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
713 &mut self.change_notifier
714 }
715}
716
717struct UndoStack<T> {
721 list: Vec<T>,
722 index: i32,
724}
725
726const K_THROTTLE_DURATION: Duration = Duration::from_millis(500);
730
731impl<T: PartialEq> UndoStack<T> {
732 fn new() -> UndoStack<T> {
734 UndoStack {
735 list: Vec::new(),
736 index: -1,
737 }
738 }
739
740 fn current_value(&self) -> Option<&T> {
742 if self.list.is_empty() {
743 None
744 } else {
745 Some(&self.list[self.index as usize])
746 }
747 }
748
749 fn can_undo(&self) -> bool {
750 !self.list.is_empty() && self.index > 0
751 }
752
753 fn can_redo(&self) -> bool {
754 !self.list.is_empty() && (self.index as usize) < self.list.len() - 1
755 }
756
757 fn push(&mut self, value: T) {
761 if self.list.is_empty() {
762 self.index = 0;
763 self.list.push(value);
764 return;
765 }
766
767 debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
768
769 if self.current_value() == Some(&value) {
770 return;
771 }
772
773 if (self.index as usize) != self.list.len() - 1 {
776 self.list.truncate((self.index as usize) + 1);
777 }
778 self.list.push(value);
779 self.index = self.list.len() as i32 - 1;
780 }
781
782 fn undo(&mut self) -> Option<&T> {
788 if self.list.is_empty() {
789 return None;
790 }
791
792 debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
793
794 if self.index != 0 {
795 self.index -= 1;
796 }
797
798 self.current_value()
799 }
800
801 fn redo(&mut self) -> Option<&T> {
807 if self.list.is_empty() {
808 return None;
809 }
810
811 debug_assert!((self.index as usize) < self.list.len() && self.index >= 0);
812
813 if (self.index as usize) < self.list.len() - 1 {
814 self.index += 1;
815 }
816
817 self.current_value()
818 }
819
820 fn clear(&mut self) {
822 self.list.clear();
823 self.index = -1;
824 }
825}
826
827impl<T: Debug> Debug for UndoStack<T> {
828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829 write!(f, "_UndoStack {:?}", self.list)
830 }
831}
832
833#[cfg(test)]
834mod tests {
835 use super::*;
836 use crate::widgets::focus_manager::FocusNode;
837 use std::cell::Cell;
838 use std::rc::Rc;
839 use std::time::Duration;
840 use waft_foundation::ListenableObject;
841 use waft_foundation::{AppCell, Listener, ValueListenable};
842
843 use crate::framework::GlobalKey;
844 use crate::test_harness::Harness;
845 use crate::widgets::basic::SizedBox;
846
847 #[test]
848 fn controller_starts_empty() {
849 let cell = AppCell::new();
850 let mut app = cell.borrow_mut();
851 let controller = UndoHistoryController::new(&mut app);
852 assert_eq!(controller.value(&app), &UndoHistoryValue::EMPTY);
853 }
854
855 #[test]
856 fn undo_notifies_on_undo_when_can_undo() {
857 let cell = AppCell::new();
858 let mut app = cell.borrow_mut();
859 let controller =
860 UndoHistoryController::from_value(&mut app, UndoHistoryValue::new().can_undo(true));
861 let fired = Rc::new(Cell::new(false));
862 let seen = Rc::clone(&fired);
863 controller
864 .on_undo(&app)
865 .add_listener(&mut app, Listener::new(move |_app| seen.set(true)));
866 controller.undo(&mut app);
867 assert!(fired.get());
868 }
869
870 #[test]
871 fn undo_is_a_no_op_when_empty() {
872 let cell = AppCell::new();
873 let mut app = cell.borrow_mut();
874 let controller = UndoHistoryController::new(&mut app);
875 let fired = Rc::new(Cell::new(false));
876 let seen = Rc::clone(&fired);
877 controller
878 .on_undo(&app)
879 .add_listener(&mut app, Listener::new(move |_app| seen.set(true)));
880 controller.undo(&mut app);
881 assert!(!fired.get());
882 }
883
884 #[test]
885 fn stack_push_undo_redo() {
886 let mut stack = UndoStack::new();
887 stack.push("a");
888 stack.push("b");
889 stack.push("c");
890 assert_eq!(stack.current_value(), Some(&"c"));
891 assert!(stack.can_undo());
892 assert!(!stack.can_redo());
893 assert_eq!(stack.undo(), Some(&"b"));
894 assert!(stack.can_redo());
895 assert_eq!(stack.redo(), Some(&"c"));
896 stack.undo();
897 stack.push("d");
898 assert_eq!(stack.current_value(), Some(&"d"));
899 assert!(!stack.can_redo());
900 assert_eq!(stack.undo(), Some(&"b"));
901 }
902
903 #[test]
904 fn push_two_values_then_undo_restores() {
905 let cell = AppCell::new();
906 let mut app = cell.borrow_mut();
907 let value = app.create(ValueNotifier::new(0i32));
908 let focus_node = FocusNode::new(&mut app);
909 let key = GlobalKey::new();
910 let notifier = value.handle();
911 let widget = UndoHistory::new(
912 value.clone(),
913 move |app, next| {
914 notifier.set_value(app, next);
915 },
916 focus_node.into_erased(),
917 SizedBox::shrink(),
918 )
919 .key(key.clone().into());
920 let harness = Harness::mount(&mut app, widget.into_widget());
921 harness.pump(&mut app);
922 drop(app);
923 cell.elapse(Duration::from_millis(500));
924
925 let mut app = cell.borrow_mut();
926 value.set_value(&mut app, 1);
927 drop(app);
928 cell.elapse(Duration::from_millis(500));
929
930 let mut app = cell.borrow_mut();
931 let state = key
932 .current_state::<UndoHistoryState<i32>>(&app)
933 .expect("the history is mounted");
934 assert!(state.can_undo(&app));
935 assert!(!state.can_redo(&app));
936 state.undo(&mut app);
937 assert_eq!(*value.value(&app), 0);
938 assert!(!state.can_undo(&app));
939 assert!(state.can_redo(&app));
940 state.redo(&mut app);
941 assert_eq!(*value.value(&app), 1);
942 }
943}