basecommand.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module undo/basecommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { transformSets } from '@ckeditor/ckeditor5-engine/src/model/operation/transform';
  10. /**
  11. * Base class for undo feature commands: {@link module:undo/undocommand~UndoCommand} and {@link module:undo/redocommand~RedoCommand}.
  12. *
  13. * @protected
  14. * @extends module:core/command~Command
  15. */
  16. export default class BaseCommand extends Command {
  17. constructor( editor ) {
  18. super( editor );
  19. /**
  20. * Stack of items stored by the command. These are pairs of:
  21. *
  22. * * {@link module:engine/model/batch~Batch batch} saved by the command,
  23. * * {@link module:engine/model/selection~Selection selection} state at the moment of saving the batch.
  24. *
  25. * @protected
  26. * @member {Array} #_stack
  27. */
  28. this._stack = [];
  29. /**
  30. * Stores all batches that were created by this command.
  31. *
  32. * @protected
  33. * @member {WeakSet.<module:engine/model/batch~Batch>} #_createdBatches
  34. */
  35. this._createdBatches = new WeakSet();
  36. // Refresh state, so the command is inactive right after initialization.
  37. this.refresh();
  38. }
  39. /**
  40. * @inheritDoc
  41. */
  42. refresh() {
  43. this.isEnabled = this._stack.length > 0;
  44. }
  45. /**
  46. * Stores a batch in the command, together with the selection state of the {@link module:engine/model/document~Document document}
  47. * created by the editor which this command is registered to.
  48. *
  49. * @param {module:engine/model/batch~Batch} batch The batch to add.
  50. */
  51. addBatch( batch ) {
  52. const docSelection = this.editor.model.document.selection;
  53. const selection = {
  54. ranges: docSelection.hasOwnRange ? Array.from( docSelection.getRanges() ) : [],
  55. isBackward: docSelection.isBackward
  56. };
  57. this._stack.push( { batch, selection } );
  58. this.refresh();
  59. }
  60. /**
  61. * Removes all items from the stack.
  62. */
  63. clearStack() {
  64. this._stack = [];
  65. this.refresh();
  66. }
  67. /**
  68. * Restores the {@link module:engine/model/document~Document#selection document selection} state after a batch was undone.
  69. *
  70. * @protected
  71. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be restored.
  72. * @param {Boolean} isBackward A flag describing whether the restored range was selected forward or backward.
  73. * @param {Array.<module:engine/model/operation/operation~Operation>} operations Operations which has been applied
  74. * since selection has been stored.
  75. */
  76. _restoreSelection( ranges, isBackward, operations ) {
  77. const model = this.editor.model;
  78. const document = model.document;
  79. // This will keep the transformed selection ranges.
  80. const selectionRanges = [];
  81. // Transform all ranges from the restored selection.
  82. for ( const range of ranges ) {
  83. const transformed = transformSelectionRange( range, operations );
  84. // For each `range` from `ranges`, we take only one transformed range.
  85. // This is because we want to prevent situation where single-range selection
  86. // got transformed to multi-range selection. We will take the first range that
  87. // is not in the graveyard.
  88. const newRange = transformed.find(
  89. range => range.start.root != document.graveyard
  90. );
  91. // `transformedRange` might be `undefined` if transformed range ended up in graveyard.
  92. if ( newRange ) {
  93. selectionRanges.push( newRange );
  94. }
  95. }
  96. // `selectionRanges` may be empty if all ranges ended up in graveyard. If that is the case, do not restore selection.
  97. if ( selectionRanges.length ) {
  98. model.change( writer => {
  99. writer.setSelection( selectionRanges, { backward: isBackward } );
  100. } );
  101. }
  102. }
  103. /**
  104. * Undoes a batch by reversing that batch, transforming reversed batch and finally applying it.
  105. * This is a helper method for {@link #execute}.
  106. *
  107. * @protected
  108. * @param {module:engine/model/batch~Batch} batchToUndo The batch to be undone.
  109. * @param {module:engine/model/batch~Batch} undoingBatch The batch that will contain undoing changes.
  110. */
  111. _undo( batchToUndo, undoingBatch ) {
  112. const model = this.editor.model;
  113. const document = model.document;
  114. // All changes done by the command execution will be saved as one batch.
  115. this._createdBatches.add( undoingBatch );
  116. const operationsToUndo = batchToUndo.operations.slice().filter( operation => operation.isDocumentOperation );
  117. operationsToUndo.reverse();
  118. // We will process each operation from `batchToUndo`, in reverse order. If there were operations A, B and C in undone batch,
  119. // we need to revert them in reverse order, so first C' (reversed C), then B', then A'.
  120. for ( const operationToUndo of operationsToUndo ) {
  121. const nextBaseVersion = operationToUndo.baseVersion + 1;
  122. const historyOperations = Array.from( document.history.getOperations( nextBaseVersion ) );
  123. const transformedSets = transformSets(
  124. [ operationToUndo.getReversed() ],
  125. historyOperations,
  126. {
  127. useContext: true,
  128. document: this.editor.model.document,
  129. padWithNoOps: false
  130. }
  131. );
  132. const reversedOperations = transformedSets.operationsA;
  133. // After reversed operation has been transformed by all history operations, apply it.
  134. for ( const operation of reversedOperations ) {
  135. // Before applying, add the operation to the `undoingBatch`.
  136. undoingBatch.addOperation( operation );
  137. model.applyOperation( operation );
  138. document.history.setOperationAsUndone( operationToUndo, operation );
  139. }
  140. }
  141. }
  142. }
  143. // Transforms given range `range` by given `operations`.
  144. // Returns an array containing one or more ranges, which are result of the transformation.
  145. function transformSelectionRange( range, operations ) {
  146. const transformed = range.getTransformedByOperations( operations );
  147. // After `range` got transformed, we have an array of ranges. Some of those
  148. // ranges may be "touching" -- they can be next to each other and could be merged.
  149. // First, we have to sort those ranges to assure that they are in order.
  150. transformed.sort( ( a, b ) => a.start.isBefore( b.start ) ? -1 : 1 );
  151. // Then, we check if two consecutive ranges are touching.
  152. for ( let i = 1; i < transformed.length; i++ ) {
  153. const a = transformed[ i - 1 ];
  154. const b = transformed[ i ];
  155. if ( a.end.isTouching( b.start ) ) {
  156. // And join them together if they are.
  157. a.end = b.end;
  158. transformed.splice( i, 1 );
  159. i--;
  160. }
  161. }
  162. return transformed;
  163. }