actions.dart 15.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Ian Hickson's avatar
Ian Hickson committed
4

5 6 7
import 'dart:collection';
import 'dart:io';

8 9 10 11
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

12
void main() {
13 14 15 16 17 18
  runApp(const MaterialApp(
    title: 'Actions Demo',
    home: FocusDemo(),
  ));
}

19 20 21 22 23
/// A class that can hold invocation information that an [UndoableAction] can
/// use to undo/redo itself.
///
/// Instances of this class are returned from [UndoableAction]s and placed on
/// the undo stack when they are invoked.
24
class Memento extends Object with Diagnosticable {
25
  const Memento({
26 27 28
    required this.name,
    required this.undo,
    required this.redo,
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  });

  /// Returns true if this Memento can be used to undo.
  ///
  /// Subclasses could override to provide their own conditions when a command is
  /// undoable.
  bool get canUndo => true;

  /// Returns true if this Memento can be used to redo.
  ///
  /// Subclasses could override to provide their own conditions when a command is
  /// redoable.
  bool get canRedo => true;

  final String name;
  final VoidCallback undo;
  final ValueGetter<Memento> redo;

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('name', name));
    properties.add(FlagProperty('undo', value: undo != null, ifTrue: 'undo'));
    properties.add(FlagProperty('redo', value: redo != null, ifTrue: 'redo'));
  }
}

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/// Undoable Actions

/// An [ActionDispatcher] subclass that manages the invocation of undoable
/// actions.
class UndoableActionDispatcher extends ActionDispatcher implements Listenable {
  /// Constructs a new [UndoableActionDispatcher].
  ///
  /// The [maxUndoLevels] argument must not be null.
  UndoableActionDispatcher({
    int maxUndoLevels = _defaultMaxUndoLevels,
  })  : assert(maxUndoLevels != null),
        _maxUndoLevels = maxUndoLevels;

  // A stack of actions that have been performed. The most recent action
  // performed is at the end of the list.
71
  final DoubleLinkedQueue<Memento> _completedActions = DoubleLinkedQueue<Memento>();
72 73
  // A stack of actions that can be redone. The most recent action performed is
  // at the end of the list.
74
  final List<Memento> _undoneActions = <Memento>[];
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

  static const int _defaultMaxUndoLevels = 1000;

  /// The maximum number of undo levels allowed.
  ///
  /// If this value is set to a value smaller than the number of completed
  /// actions, then the stack of completed actions is truncated to only include
  /// the last [maxUndoLevels] actions.
  int get maxUndoLevels => _maxUndoLevels;
  int _maxUndoLevels;
  set maxUndoLevels(int value) {
    _maxUndoLevels = value;
    _pruneActions();
  }

  final Set<VoidCallback> _listeners = <VoidCallback>{};

  @override
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  @override
  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }

  /// Notifies listeners that the [ActionDispatcher] has changed state.
  ///
  /// May only be called by subclasses.
  @protected
  void notifyListeners() {
107
    for (final VoidCallback callback in _listeners) {
108 109 110 111 112
      callback();
    }
  }

  @override
113 114
  Object? invokeAction(Action<Intent> action, Intent intent, [BuildContext? context]) {
    final Object? result = super.invokeAction(action, intent, context);
115 116
    print('Invoking ${action is UndoableAction ? 'undoable ' : ''}$intent as $action: $this ');
    if (action is UndoableAction) {
117
      _completedActions.addLast(result! as Memento);
118 119 120 121 122 123 124 125 126 127
      _undoneActions.clear();
      _pruneActions();
      notifyListeners();
    }
    return result;
  }

  // Enforces undo level limit.
  void _pruneActions() {
    while (_completedActions.length > _maxUndoLevels) {
128
      _completedActions.removeFirst();
129 130 131 132 133 134
    }
  }

  /// Returns true if there is an action on the stack that can be undone.
  bool get canUndo {
    if (_completedActions.isNotEmpty) {
135
      return _completedActions.first.canUndo;
136 137 138 139 140 141 142
    }
    return false;
  }

  /// Returns true if an action that has been undone can be re-invoked.
  bool get canRedo {
    if (_undoneActions.isNotEmpty) {
143
      return _undoneActions.first.canRedo;
144 145 146 147 148 149 150 151 152 153 154 155
    }
    return false;
  }

  /// Undoes the last action executed if possible.
  ///
  /// Returns true if the action was successfully undone.
  bool undo() {
    print('Undoing. $this');
    if (!canUndo) {
      return false;
    }
156 157 158
    final Memento memento = _completedActions.removeLast();
    memento.undo();
    _undoneActions.add(memento);
159 160 161 162 163 164 165 166 167 168 169 170
    notifyListeners();
    return true;
  }

  /// Re-invokes a previously undone action, if possible.
  ///
  /// Returns true if the action was successfully invoked.
  bool redo() {
    print('Redoing. $this');
    if (!canRedo) {
      return false;
    }
171 172 173
    final Memento memento = _undoneActions.removeLast();
    final Memento replacement = memento.redo();
    _completedActions.add(replacement);
174 175 176 177 178 179 180 181 182 183
    _pruneActions();
    notifyListeners();
    return true;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('undoable items', _completedActions.length));
    properties.add(IntProperty('redoable items', _undoneActions.length));
184 185
    properties.add(IterableProperty<Memento>('undo stack', _completedActions));
    properties.add(IterableProperty<Memento>('redo stack', _undoneActions));
186 187 188 189
  }
}

class UndoIntent extends Intent {
190 191
  const UndoIntent();
}
192

193
class UndoAction extends Action<UndoIntent> {
194
  @override
195
  bool isEnabled(UndoIntent intent) {
196 197 198 199 200
    final BuildContext? buildContext = primaryFocus?.context ?? FocusDemo.appKey.currentContext;
    if (buildContext == null) {
      return false;
    }
    final UndoableActionDispatcher manager = Actions.of(buildContext) as UndoableActionDispatcher;
201 202
    return manager.canUndo;
  }
203 204 205

  @override
  void invoke(UndoIntent intent) {
206 207 208 209 210 211
    final BuildContext? buildContext = primaryFocus?.context ?? FocusDemo.appKey.currentContext;
    if (buildContext == null) {
      return;
    }
    final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext!) as UndoableActionDispatcher;
    manager.undo();
212
  }
213 214 215
}

class RedoIntent extends Intent {
216 217
  const RedoIntent();
}
218

219
class RedoAction extends Action<RedoIntent> {
220
  @override
221
  bool isEnabled(RedoIntent intent) {
222 223 224 225 226
    final BuildContext? buildContext = primaryFocus?.context ?? FocusDemo.appKey.currentContext;
    if (buildContext == null) {
      return false;
    }
    final UndoableActionDispatcher manager = Actions.of(buildContext) as UndoableActionDispatcher;
227 228 229
    return manager.canRedo;
  }

230 231
  @override
  RedoAction invoke(RedoIntent intent) {
232 233 234 235 236 237
    final BuildContext? buildContext = primaryFocus?.context ?? FocusDemo.appKey.currentContext;
    if (buildContext == null) {
      return this;
    }
    final UndoableActionDispatcher manager = Actions.of(buildContext) as UndoableActionDispatcher;
    manager.redo();
238 239 240
    return this;
  }
}
241 242

/// An action that can be undone.
243
abstract class UndoableAction<T extends Intent> extends Action<T> {
244
  /// The [Intent] this action was originally invoked with.
245 246
  Intent? get invocationIntent => _invocationTag;
  Intent? _invocationTag;
247 248

  @protected
249
  set invocationIntent(Intent? value) => _invocationTag = value;
250 251 252

  @override
  @mustCallSuper
253
  void invoke(T intent) {
254
    invocationIntent = intent;
255 256 257
  }
}

258
class UndoableFocusActionBase<T extends Intent> extends UndoableAction<T> {
259
  @override
260 261 262
  @mustCallSuper
  Memento invoke(T intent) {
    super.invoke(intent);
263 264
    final FocusNode? previousFocus = primaryFocus;
    return Memento(name: previousFocus!.debugLabel!, undo: () {
265 266 267 268
      previousFocus.requestFocus();
    }, redo: () {
      return invoke(intent);
    });
269 270 271
  }
}

272
class UndoableRequestFocusAction extends UndoableFocusActionBase<RequestFocusIntent> {
273
  @override
274 275 276 277
  Memento invoke(RequestFocusIntent intent) {
    final Memento memento = super.invoke(intent);
    intent.focusNode.requestFocus();
    return memento;
278 279 280 281
  }
}

/// Actions for manipulating focus.
282
class UndoableNextFocusAction extends UndoableFocusActionBase<NextFocusIntent> {
283
  @override
284 285
  Memento invoke(NextFocusIntent intent) {
    final Memento memento = super.invoke(intent);
286
    primaryFocus?.nextFocus();
287
    return memento;
288 289 290
  }
}

291
class UndoablePreviousFocusAction extends UndoableFocusActionBase<PreviousFocusIntent> {
292
  @override
293 294
  Memento invoke(PreviousFocusIntent intent) {
    final Memento memento = super.invoke(intent);
295
    primaryFocus?.previousFocus();
296
    return memento;
297 298 299
  }
}

300
class UndoableDirectionalFocusAction extends UndoableFocusActionBase<DirectionalFocusIntent> {
301
  TraversalDirection? direction;
302 303

  @override
304 305
  Memento invoke(DirectionalFocusIntent intent) {
    final Memento memento = super.invoke(intent);
306
    primaryFocus?.focusInDirection(intent.direction);
307
    return memento;
308 309 310 311 312
  }
}

/// A button class that takes focus when clicked.
class DemoButton extends StatefulWidget {
313
  const DemoButton({super.key, required this.name});
314 315 316 317

  final String name;

  @override
318
  State<DemoButton> createState() => _DemoButtonState();
319 320 321
}

class _DemoButtonState extends State<DemoButton> {
322
  late final FocusNode _focusNode = FocusNode(debugLabel: widget.name);
323
  final GlobalKey _nameKey = GlobalKey();
324 325 326 327

  void _handleOnPressed() {
    print('Button ${widget.name} pressed.');
    setState(() {
328
      Actions.invoke(_nameKey.currentContext!, RequestFocusIntent(_focusNode));
329 330 331 332 333 334 335 336 337 338 339
    });
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
340
    return TextButton(
341
      focusNode: _focusNode,
342
      style: ButtonStyle(
343
        foregroundColor: const MaterialStatePropertyAll<Color>(Colors.black),
344
        overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
345
          if (states.contains(MaterialState.focused)) {
346
            return Colors.red;
347 348
          }
          if (states.contains(MaterialState.hovered)) {
349
            return Colors.blue;
350
          }
351
          return Colors.transparent;
352 353
        }),
      ),
354
      onPressed: () => _handleOnPressed(),
355
      child: Text(widget.name, key: _nameKey),
356 357 358 359 360
    );
  }
}

class FocusDemo extends StatefulWidget {
361
  const FocusDemo({super.key});
362

363 364
  static GlobalKey appKey = GlobalKey();

365
  @override
366
  State<FocusDemo> createState() => _FocusDemoState();
367 368 369
}

class _FocusDemoState extends State<FocusDemo> {
370 371 372 373
  final FocusNode outlineFocus = FocusNode(debugLabel: 'Demo Focus Node');
  late final UndoableActionDispatcher dispatcher = UndoableActionDispatcher();
  bool canUndo = false;
  bool canRedo = false;
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

  @override
  void initState() {
    super.initState();
    canUndo = dispatcher.canUndo;
    canRedo = dispatcher.canRedo;
    dispatcher.addListener(_handleUndoStateChange);
  }

  void _handleUndoStateChange() {
    if (dispatcher.canUndo != canUndo) {
      setState(() {
        canUndo = dispatcher.canUndo;
      });
    }
    if (dispatcher.canRedo != canRedo) {
      setState(() {
        canRedo = dispatcher.canRedo;
      });
    }
  }

  @override
  void dispose() {
    dispatcher.removeListener(_handleUndoStateChange);
    outlineFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final TextTheme textTheme = Theme.of(context).textTheme;
406 407
    return Actions(
      dispatcher: dispatcher,
408 409 410 411 412 413 414
      actions: <Type, Action<Intent>>{
        RequestFocusIntent: UndoableRequestFocusAction(),
        NextFocusIntent: UndoableNextFocusAction(),
        PreviousFocusIntent: UndoablePreviousFocusAction(),
        DirectionalFocusIntent: UndoableDirectionalFocusAction(),
        UndoIntent: UndoAction(),
        RedoIntent: RedoAction(),
415
      },
416
      child: FocusTraversalGroup(
417 418
        policy: ReadingOrderTraversalPolicy(),
        child: Shortcuts(
419 420 421
          shortcuts: <ShortcutActivator, Intent>{
            SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS, shift: true): const RedoIntent(),
            SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS): const UndoIntent(),
422 423
          },
          child: FocusScope(
424
            key: FocusDemo.appKey,
425 426 427
            debugLabel: 'Scope',
            autofocus: true,
            child: DefaultTextStyle(
428
              style: textTheme.headlineMedium!,
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
              child: Scaffold(
                appBar: AppBar(
                  title: const Text('Actions Demo'),
                ),
                body: Center(
                  child: Builder(builder: (BuildContext context) {
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'One'),
                            DemoButton(name: 'Two'),
                            DemoButton(name: 'Three'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'Four'),
                            DemoButton(name: 'Five'),
                            DemoButton(name: 'Six'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const <Widget>[
                            DemoButton(name: 'Seven'),
                            DemoButton(name: 'Eight'),
                            DemoButton(name: 'Nine'),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.all(8.0),
467
                              child: ElevatedButton(
468 469
                                onPressed: canUndo
                                    ? () {
470
                                        Actions.invoke(context, const UndoIntent());
471 472
                                      }
                                    : null,
473
                                child: const Text('UNDO'),
474
                              ),
475 476 477
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
478
                              child: ElevatedButton(
479 480
                                onPressed: canRedo
                                    ? () {
481
                                        Actions.invoke(context, const RedoIntent());
482 483
                                      }
                                    : null,
484
                                child: const Text('REDO'),
485
                              ),
486 487 488 489 490 491
                            ),
                          ],
                        ),
                      ],
                    );
                  }),
492 493 494 495 496 497 498 499 500
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}