Skip to main content

waft_widgets/widgets/
undo_history.rs

1//! Flutter counterpart: `widgets/undo_history.dart`.
2
3use 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
26/// Called when an undo or redo causes a state change.
27pub type UndoHistoryOnTriggered<T> = Rc<dyn Fn(&mut App, T)>;
28
29/// Called when checking whether a value change should be pushed onto the undo stack.
30pub type ShouldChangeUndoStack<T> = Rc<dyn Fn(Option<&T>, &T) -> bool>;
31
32/// Called right before a new entry is pushed to the undo stack.
33pub type UndoStackModifier<T> = Rc<dyn Fn(T) -> T>;
34
35/// Provides undo/redo capabilities for a [`ValueNotifier`].
36///
37/// Listens to [`value`](Self::value) and saves relevant values for undoing/redoing. The
38/// cadence at which values are saved is a best approximation of the native
39/// behaviors of a number of hardware keyboard on Flutter's desktop
40/// platforms, as there are subtle differences between each of the platforms.
41///
42/// Listens to keyboard undo/redo shortcuts and calls [`on_triggered`](Self::on_triggered) when a
43/// shortcut is triggered that would affect the state of the [`value`](Self::value).
44///
45/// The [`child`](Self::child) must manage focus on the [`focus_node`](Self::focus_node). For
46/// example, using a `TextField` or `Focus` widget.
47///
48/// The [`value`](Self::value) is any kept [`ValueListenable`], which Dart types as a
49/// `ValueNotifier<T>`: a `Ref<ValueNotifier<T>>`, or a `TextEditingControllerRef`.
50pub struct UndoHistory<
51    T: Clone + PartialEq + 'static,
52    V: ValueListenable<T> + Clone + PartialEq + 'static = Ref<ValueNotifier<T>>,
53> {
54    /// See [`Widget::key`](crate::Widget::key).
55    pub key: Option<KeyRef>,
56    /// Called when checking whether a value change should be pushed onto
57    /// the undo stack.
58    pub should_change_undo_stack: Option<ShouldChangeUndoStack<T>>,
59    /// The value to track over time.
60    pub value: V,
61    /// Called when an undo or redo causes a state change.
62    ///
63    /// If the state would still be the same before and after the undo/redo, this
64    /// will not be called. For example, receiving a redo when there is nothing
65    /// to redo will not call this method.
66    ///
67    /// Changes to the [`value`](Self::value) while this method is running will not be recorded
68    /// on the undo stack. For example, a `TextInputFormatter` may change the value
69    /// from what was on the undo stack, but this new value will not be recorded,
70    /// as that would wipe out the redo history.
71    pub on_triggered: UndoHistoryOnTriggered<T>,
72    /// The [`FocusNode`] that will be used to listen for focus to set the initial
73    /// undo state for the element.
74    pub focus_node: FocusNodeRef,
75    /// Called right before a new entry is pushed to the undo stack.
76    ///
77    /// The value returned from this method will be pushed to the stack instead
78    /// of the original value.
79    ///
80    /// If null then the original value will always be pushed to the stack.
81    pub undo_stack_modifier: Option<UndoStackModifier<T>>,
82    /// Controls the undo state.
83    ///
84    /// If null, this widget will create its own [`UndoHistoryController`].
85    pub controller: Option<Ref<UndoHistoryController>>,
86    /// The child widget of [`UndoHistory`].
87    pub child: WidgetRef,
88}
89
90impl<T: Clone + PartialEq + 'static, V: ValueListenable<T> + Clone + PartialEq + 'static>
91    UndoHistory<T, V>
92{
93    /// Creates an instance of [`UndoHistory`].
94    #[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    /// Dart `UndoHistory(key:)`.
114    pub fn key(mut self, key: KeyRef) -> UndoHistory<T, V> {
115        self.key = Some(key);
116        self
117    }
118
119    /// Dart `UndoHistory(shouldChangeUndoStack:)`.
120    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    /// Dart `UndoHistory(undoStackModifier:)`.
129    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    /// Dart `UndoHistory(controller:)`.
138    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
176/// State for a [`UndoHistory`].
177///
178/// Provides [`undo`](Self::undo), [`redo`](Self::redo), [`can_undo`](Self::can_undo), and
179/// [`can_redo`](Self::can_redo) for programmatic access to the undo state for custom undo
180/// and redo UI implementations.
181pub 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    // Record the last value to prevent pushing multiple
191    // of the same value in a row onto the undo stack. For example, push gets
192    // called both in initState and when the EditableText receives focus.
193    last_value: Option<T>,
194    controller: Option<Ref<UndoHistoryController>>,
195}
196
197/// Dart's `try`/`finally` around `_duringTrigger`. Holds the flag by `Rc`, never
198/// a borrow of the state, so a panic still clears it.
199struct 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    /// Reverts the value on the stack to the previous value.
235    pub fn undo(self: Handle<Self>, app: &mut App) {
236        if app.get(self).stack.current_value().is_none() {
237            // Returns early if there is not a first value registered in the history.
238            // This is important because, if an undo is received while the initial
239            // value is being pushed (a.k.a when the field gets the focus but the
240            // throttling delay is pending), the initial push should not be canceled.
241            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); // Cancel ongoing push, if any.
250            }
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    /// Updates the value on the stack to the next value.
261    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    /// Will be true if there are past values on the stack.
268    pub fn can_undo(self: Handle<Self>, app: &App) -> bool {
269        app.get(self).stack.can_undo()
270    }
271
272    /// Will be true if there are future values on the stack.
273    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(&current) {
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(), &current)
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    /// Dart's `_throttledPush`: one pending call, latest arg wins.
365    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/// Represents whether the current undo stack can undo or redo.
542#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
543pub struct UndoHistoryValue {
544    /// Whether the current undo stack can perform an undo operation.
545    pub can_undo: bool,
546    /// Whether the current undo stack can perform a redo operation.
547    pub can_redo: bool,
548}
549
550impl UndoHistoryValue {
551    /// A value corresponding to an undo stack that can neither undo nor redo.
552    pub const EMPTY: UndoHistoryValue = UndoHistoryValue {
553        can_undo: false,
554        can_redo: false,
555    };
556
557    /// Creates a value for whether the current undo stack can undo or redo.
558    ///
559    /// The [`can_undo`](Self::can_undo) and [`can_redo`](Self::can_redo) arguments must have a
560    /// value, but default to false.
561    pub const fn new() -> UndoHistoryValue {
562        UndoHistoryValue::EMPTY
563    }
564
565    /// Dart `UndoHistoryValue(canUndo:)`.
566    pub const fn can_undo(mut self, can_undo: bool) -> UndoHistoryValue {
567        self.can_undo = can_undo;
568        self
569    }
570
571    /// Dart `UndoHistoryValue(canRedo:)`.
572    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    /// Dart's `UndoHistoryValue.toString`.
586    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
595/// A controller for the undo history, for example for an editable text field.
596///
597/// Whenever a change happens to the underlying value that the `UndoHistory` widget tracks,
598/// that widget updates the [`value`](Self::value) and the controller notifies its listeners.
599/// Listeners can then read the [`can_undo`](UndoHistoryValue::can_undo) and
600/// [`can_redo`](UndoHistoryValue::can_redo) properties of the value to discover whether
601/// [`undo`](Self::undo) or [`redo`](Self::redo) are possible.
602///
603/// The controller also has [`undo`](Self::undo) and [`redo`](Self::redo) methods to modify
604/// the undo history.
605///
606/// See also:
607///
608///  * `EditableText`, which uses the `UndoHistory` widget and allows control of the
609///    underlying history using an [`UndoHistoryController`].
610pub 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    /// Creates a controller for an `UndoHistory` widget.
627    pub fn new(app: &mut App) -> Ref<UndoHistoryController> {
628        Self::from_value(app, UndoHistoryValue::EMPTY)
629    }
630
631    /// Dart `UndoHistoryController(value:)`.
632    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    /// The current undo/redo capability.
644    pub fn value(self: Handle<Self>, app: &App) -> &UndoHistoryValue {
645        &app.get(self).value
646    }
647
648    /// Setting this notifies listeners when the value differs.
649    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    /// Notifies listeners that [`undo`](Self::undo) has been called.
658    pub fn on_undo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
659        app.get(self).on_undo.handle()
660    }
661
662    /// Notifies listeners that [`redo`](Self::redo) has been called.
663    pub fn on_redo(self: Handle<Self>, app: &App) -> Handle<ChangeNotifierData> {
664        app.get(self).on_redo.handle()
665    }
666
667    /// Reverts the value on the stack to the previous value.
668    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    /// Updates the value on the stack to the next value.
677    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    /// Discards any resources used by the object.
686    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    /// Dart's `UndoHistoryController.toString`, which it inherits from
697    /// `ValueNotifier<UndoHistoryValue>`: the identity and the value.
698    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
717/// A data structure representing a chronological list of states that can be undone and redone.
718///
719/// Dart's `_UndoStack`.
720struct UndoStack<T> {
721    list: Vec<T>,
722    // The index of the current value, or -1 if the list is empty.
723    index: i32,
724}
725
726// This duration was chosen as a best fit for the behavior of Mac, Linux,
727// and Windows undo/redo state save durations, but it is not perfect for any
728// of them.
729const K_THROTTLE_DURATION: Duration = Duration::from_millis(500);
730
731impl<T: PartialEq> UndoStack<T> {
732    /// Creates an instance of [`UndoStack`].
733    fn new() -> UndoStack<T> {
734        UndoStack {
735            list: Vec::new(),
736            index: -1,
737        }
738    }
739
740    /// Returns the current value of the stack.
741    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    /// Add a new state change to the stack.
758    ///
759    /// Pushing identical objects will not create multiple entries.
760    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 anything has been undone in this stack, remove those irrelevant states
774        // before adding the new one.
775        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    /// Returns the current value after an undo operation.
783    ///
784    /// An undo operation moves the current value to the previously pushed value, if any.
785    ///
786    /// Iff the stack is completely empty, then returns null.
787    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    /// Returns the current value after a redo operation.
802    ///
803    /// A redo operation moves the current value to the value that was last undone, if any.
804    ///
805    /// Iff the stack is completely empty, then returns null.
806    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    /// Remove everything from the stack.
821    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}