undocommand.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  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. const undoingBatch = this.editor.model.createBatch( 'transparent' );
  33. // All changes has to be done in one `enqueueChange` callback so other listeners will not
  34. // step between consecutive operations, or won't do changes to the document before selection is properly restored.
  35. this.editor.model.enqueueChange( undoingBatch, () => {
  36. this._undo( item.batch, undoingBatch );
  37. const operations = this.editor.model.document.history.getOperations( item.batch.baseVersion );
  38. this._restoreSelection( item.selection.ranges, item.selection.isBackward, operations );
  39. this.fire( 'revert', item.batch, undoingBatch );
  40. } );
  41. this.refresh();
  42. }
  43. }
  44. /**
  45. * Fired when execution of the command reverts some batch.
  46. *
  47. * @event revert
  48. */