undocommand.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module undo/undocommand
  7. */
  8. import BaseCommand from './basecommand';
  9. /**
  10. * The undo command stores {@link module:engine/model/batch~Batch batches} applied to the
  11. * {@link module:engine/model/document~Document document} and is able to undo a batch by reversing it and transforming by
  12. * batches from {@link module:engine/model/document~Document#history history} that happened after the reversed batch.
  13. *
  14. * The undo command also takes care of restoring the {@link module:engine/model/document~Document#selection document selection}.
  15. *
  16. * @extends module:undo/basecommand~BaseCommand
  17. */
  18. export default class UndoCommand extends BaseCommand {
  19. /**
  20. * Executes the command. This method reverts a {@link module:engine/model/batch~Batch batch} added to the command's stack, transforms
  21. * and applies the reverted version on the {@link module:engine/model/document~Document document} and removes the batch from the stack.
  22. * Then, it restores the {@link module:engine/model/document~Document#selection document selection}.
  23. *
  24. * @fires execute
  25. * @fires revert
  26. * @param {module:engine/model/batch~Batch} [batch] A batch that should be undone. If not set, the last added batch will be undone.
  27. */
  28. execute( batch = null ) {
  29. // If batch is not given, set `batchIndex` to the last index in command stack.
  30. const batchIndex = batch ? this._stack.findIndex( a => a.batch == batch ) : this._stack.length - 1;
  31. const item = this._stack.splice( batchIndex, 1 )[ 0 ];
  32. // All changes has to be done in one `enqueueChanges` callback so other listeners will not
  33. // step between consecutive deltas, or won't do changes to the document before selection is properly restored.
  34. this.editor.model.enqueueChange( () => {
  35. const undoingBatch = this._undo( item.batch );
  36. const deltas = this.editor.model.document.history.getDeltas( item.batch.baseVersion );
  37. this._restoreSelection( item.selection.ranges, item.selection.isBackward, deltas );
  38. this.fire( 'revert', item.batch, undoingBatch );
  39. } );
  40. this.refresh();
  41. }
  42. }
  43. /**
  44. * Fired when execution of the command reverts some batch.
  45. *
  46. * @event revert
  47. */