basecommand.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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/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. const transformedRangeGroups = ranges.map( range => range.getTransformedByOperations( operations ) );
  83. const allRanges = transformedRangeGroups.flat();
  84. for ( const rangeGroup of transformedRangeGroups ) {
  85. // While transforming there could appear ranges that are contained by other ranges, we shall ignore them.
  86. const transformed = rangeGroup.filter( range => !isRangeContainedByAnyOtherRange( range, allRanges ) );
  87. // After the range got transformed, we have an array of ranges. Some of those
  88. // ranges may be "touching" -- they can be next to each other and could be merged.
  89. normalizeRanges( transformed );
  90. // For each `range` from `ranges`, we take only one transformed range.
  91. // This is because we want to prevent situation where single-range selection
  92. // got transformed to multi-range selection. We will take the first range that
  93. // is not in the graveyard.
  94. const newRange = transformed.find(
  95. range => range.root != document.graveyard
  96. );
  97. // `transformedRange` might be `undefined` if transformed range ended up in graveyard.
  98. if ( newRange ) {
  99. selectionRanges.push( newRange );
  100. }
  101. }
  102. // @if CK_DEBUG_ENGINE // console.log( `Restored selection by undo: ${ selectionRanges.join( ', ' ) }` );
  103. // `selectionRanges` may be empty if all ranges ended up in graveyard. If that is the case, do not restore selection.
  104. if ( selectionRanges.length ) {
  105. model.change( writer => {
  106. writer.setSelection( selectionRanges, { backward: isBackward } );
  107. } );
  108. }
  109. }
  110. /**
  111. * Undoes a batch by reversing that batch, transforming reversed batch and finally applying it.
  112. * This is a helper method for {@link #execute}.
  113. *
  114. * @protected
  115. * @param {module:engine/model/batch~Batch} batchToUndo The batch to be undone.
  116. * @param {module:engine/model/batch~Batch} undoingBatch The batch that will contain undoing changes.
  117. */
  118. _undo( batchToUndo, undoingBatch ) {
  119. const model = this.editor.model;
  120. const document = model.document;
  121. // All changes done by the command execution will be saved as one batch.
  122. this._createdBatches.add( undoingBatch );
  123. const operationsToUndo = batchToUndo.operations.slice().filter( operation => operation.isDocumentOperation );
  124. operationsToUndo.reverse();
  125. // We will process each operation from `batchToUndo`, in reverse order. If there were operations A, B and C in undone batch,
  126. // we need to revert them in reverse order, so first C' (reversed C), then B', then A'.
  127. for ( const operationToUndo of operationsToUndo ) {
  128. const nextBaseVersion = operationToUndo.baseVersion + 1;
  129. const historyOperations = Array.from( document.history.getOperations( nextBaseVersion ) );
  130. const transformedSets = transformSets(
  131. [ operationToUndo.getReversed() ],
  132. historyOperations,
  133. {
  134. useRelations: true,
  135. document: this.editor.model.document,
  136. padWithNoOps: false,
  137. forceWeakRemove: true
  138. }
  139. );
  140. const reversedOperations = transformedSets.operationsA;
  141. // After reversed operation has been transformed by all history operations, apply it.
  142. for ( const operation of reversedOperations ) {
  143. // Before applying, add the operation to the `undoingBatch`.
  144. undoingBatch.addOperation( operation );
  145. model.applyOperation( operation );
  146. document.history.setOperationAsUndone( operationToUndo, operation );
  147. }
  148. }
  149. }
  150. }
  151. // Normalizes list of ranges by joining intersecting or "touching" ranges.
  152. //
  153. // @param {Array.<module:engine/model/range~Range>} ranges
  154. //
  155. function normalizeRanges( ranges ) {
  156. ranges.sort( ( a, b ) => a.start.isBefore( b.start ) ? -1 : 1 );
  157. for ( let i = 1; i < ranges.length; i++ ) {
  158. const previousRange = ranges[ i - 1 ];
  159. const joinedRange = previousRange.getJoined( ranges[ i ], true );
  160. if ( joinedRange ) {
  161. // Replace the ranges on the list with the new joined range.
  162. i--;
  163. ranges.splice( i, 2, joinedRange );
  164. }
  165. }
  166. }
  167. function isRangeContainedByAnyOtherRange( range, ranges ) {
  168. return ranges.some( otherRange => otherRange !== range && otherRange.containsRange( range, true ) );
  169. }