8
0

undoengine.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import Feature from '../feature.js';
  7. import UndoCommand from './undocommand.js';
  8. /**
  9. * Undo engine feature.
  10. *
  11. * Undo features brings in possibility to undo and re-do changes done in Tree Model by deltas through Batch API.
  12. *
  13. * @memberOf undo
  14. */
  15. export default class UndoEngine extends Feature {
  16. constructor( editor ) {
  17. super( editor );
  18. /**
  19. * Undo command which manages undo {@link engine.model.Batch batches} stack (history).
  20. * Created and registered during {@link undo.UndoEngine#init feature initialization}.
  21. *
  22. * @private
  23. * @member {undo.UndoEngineCommand} undo.UndoEngine#_undoCommand
  24. */
  25. this._undoCommand = null;
  26. /**
  27. * Undo command which manages redo {@link engine.model.Batch batches} stack (history).
  28. * Created and registered during {@link undo.UndoEngine#init feature initialization}.
  29. *
  30. * @private
  31. * @member {undo.UndoEngineCommand} undo.UndoEngine#_redoCommand
  32. */
  33. this._redoCommand = null;
  34. /**
  35. * Keeps track of which batch has already been added to undo manager.
  36. *
  37. * @private
  38. * @member {WeakSet.<engine.model.Batch>} undo.UndoEngine#_batchRegistry
  39. */
  40. this._batchRegistry = new WeakSet();
  41. }
  42. /**
  43. * @inheritDoc
  44. */
  45. init() {
  46. // Create commands.
  47. this._redoCommand = new UndoCommand( this.editor );
  48. this._undoCommand = new UndoCommand( this.editor );
  49. // Register command to the editor.
  50. this.editor.commands.set( 'redo', this._redoCommand );
  51. this.editor.commands.set( 'undo', this._undoCommand );
  52. this.listenTo( this.editor.document, 'change', ( evt, type, changes, batch ) => {
  53. // Whenever a new batch is created add it to the undo history and clear redo history.
  54. if ( batch && !this._batchRegistry.has( batch ) ) {
  55. this._batchRegistry.add( batch );
  56. this._undoCommand.addBatch( batch );
  57. this._redoCommand.clearStack();
  58. }
  59. } );
  60. // Whenever batch is reverted by undo command, add it to redo history.
  61. this.listenTo( this._redoCommand, 'revert', ( evt, batch ) => {
  62. this._undoCommand.addBatch( batch );
  63. } );
  64. // Whenever batch is reverted by redo command, add it to undo history.
  65. this.listenTo( this._undoCommand, 'revert', ( evt, batch ) => {
  66. this._redoCommand.addBatch( batch );
  67. } );
  68. }
  69. }