8
0

basecommand.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /**
  2. * @license Copyright (c) 2003-2017, 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. /**
  10. * Base class for undo feature commands: {@link module:undo/undocommand~UndoCommand} and {@link module:undo/redocommand~RedoCommand}.
  11. *
  12. * @protected
  13. * @extends module:core/command~Command
  14. */
  15. export default class BaseCommand extends Command {
  16. constructor( editor ) {
  17. super( editor );
  18. /**
  19. * Stack of items stored by the command. These are pairs of:
  20. *
  21. * * {@link module:engine/model/batch~Batch batch} saved by the command,
  22. * * {@link module:engine/model/selection~Selection selection} state at the moment of saving the batch.
  23. *
  24. * @protected
  25. * @member {Array} #_stack
  26. */
  27. this._stack = [];
  28. /**
  29. * Stores all batches that were created by this command.
  30. *
  31. * @protected
  32. * @member {WeakSet.<module:engine/model/batch~Batch>} #_createdBatches
  33. */
  34. this._createdBatches = new WeakSet();
  35. // Refresh state, so the command is inactive right after initialization.
  36. this.refresh();
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. refresh() {
  42. this.isEnabled = this._stack.length > 0;
  43. }
  44. /**
  45. * Stores a batch in the command, together with the selection state of the {@link module:engine/model/document~Document document}
  46. * created by the editor which this command is registered to.
  47. *
  48. * @param {module:engine/model/batch~Batch} batch The batch to add.
  49. */
  50. addBatch( batch ) {
  51. const docSelection = this.editor.document.selection;
  52. const selection = {
  53. ranges: docSelection.hasOwnRange ? Array.from( docSelection.getRanges() ) : [],
  54. isBackward: docSelection.isBackward
  55. };
  56. this._stack.push( { batch, selection } );
  57. this.refresh();
  58. }
  59. /**
  60. * Removes all items from the stack.
  61. */
  62. clearStack() {
  63. this._stack = [];
  64. this.refresh();
  65. }
  66. /**
  67. * Restores the {@link module:engine/model/document~Document#selection document selection} state after a batch was undone.
  68. *
  69. * @protected
  70. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be restored.
  71. * @param {Boolean} isBackward A flag describing whether the restored range was selected forward or backward.
  72. * @param {Array.<module:engine/model/delta/delta~Delta>} deltas Deltas which has been applied since selection has been stored.
  73. */
  74. _restoreSelection( ranges, isBackward, deltas ) {
  75. const document = this.editor.document;
  76. // This will keep the transformed selection ranges.
  77. const selectionRanges = [];
  78. // Transform all ranges from the restored selection.
  79. for ( const range of ranges ) {
  80. const transformedRanges = transformSelectionRange( range, deltas );
  81. // For each `range` from `ranges`, we take only one transformed range.
  82. // This is because we want to prevent situation where single-range selection
  83. // got transformed to multi-range selection. We will take the first range that
  84. // is not in the graveyard.
  85. const transformedRange = transformedRanges.find(
  86. range => range.start.root != document.graveyard
  87. );
  88. // `transformedRange` might be `undefined` if transformed range ended up in graveyard.
  89. if ( transformedRange ) {
  90. selectionRanges.push( transformedRange );
  91. }
  92. }
  93. // `selectionRanges` may be empty if all ranges ended up in graveyard. If that is the case, do not restore selection.
  94. if ( selectionRanges.length ) {
  95. document.selection.setRanges( selectionRanges, isBackward );
  96. }
  97. }
  98. /**
  99. * Undoes a batch by reversing that batch, transforming reversed batch and finally applying it.
  100. * This is a helper method for {@link #execute}.
  101. *
  102. * @protected
  103. * @param {module:engine/model/batch~Batch} batchToUndo The batch to be undone.
  104. */
  105. _undo( batchToUndo ) {
  106. const document = this.editor.document;
  107. // All changes done by the command execution will be saved as one batch.
  108. const undoingBatch = document.batch();
  109. this._createdBatches.add( undoingBatch );
  110. const deltasToUndo = batchToUndo.deltas.slice();
  111. deltasToUndo.reverse();
  112. // We will process each delta from `batchToUndo`, in reverse order. If there were deltas A, B and C in undone batch,
  113. // we need to revert them in reverse order, so first C' (reversed C), then B', then A'.
  114. for ( const deltaToUndo of deltasToUndo ) {
  115. // Keep in mind that transformation algorithms return arrays. That's because the transformation might result in multiple
  116. // deltas, so we need arrays to handle them. To simplify algorithms, it is better to always operate on arrays.
  117. const nextBaseVersion = deltaToUndo.baseVersion + deltaToUndo.operations.length;
  118. // Reverse delta from the history.
  119. const historyDeltas = Array.from( document.history.getDeltas( nextBaseVersion ) );
  120. const transformedSets = document.transformDeltas( [ deltaToUndo.getReversed() ], historyDeltas, true );
  121. const reversedDeltas = transformedSets.deltasA;
  122. // After reversed delta has been transformed by all history deltas, apply it.
  123. for ( const delta of reversedDeltas ) {
  124. // Fix base version.
  125. delta.baseVersion = document.version;
  126. // Before applying, add the delta to the `undoingBatch`.
  127. undoingBatch.addDelta( delta );
  128. // Now, apply all operations of the delta.
  129. for ( const operation of delta.operations ) {
  130. document.applyOperation( operation );
  131. }
  132. document.history.setDeltaAsUndone( deltaToUndo, delta );
  133. }
  134. }
  135. return undoingBatch;
  136. }
  137. }
  138. // Transforms given range `range` by given `deltas`.
  139. // Returns an array containing one or more ranges, which are result of the transformation.
  140. function transformSelectionRange( range, deltas ) {
  141. const transformed = transformRangesByDeltas( [ range ], deltas );
  142. // After `range` got transformed, we have an array of ranges. Some of those
  143. // ranges may be "touching" -- they can be next to each other and could be merged.
  144. // First, we have to sort those ranges to assure that they are in order.
  145. transformed.sort( ( a, b ) => a.start.isBefore( b.start ) ? -1 : 1 );
  146. // Then, we check if two consecutive ranges are touching.
  147. for ( let i = 1; i < transformed.length; i++ ) {
  148. const a = transformed[ i - 1 ];
  149. const b = transformed[ i ];
  150. if ( a.end.isTouching( b.start ) ) {
  151. // And join them together if they are.
  152. a.end = b.end;
  153. transformed.splice( i, 1 );
  154. i--;
  155. }
  156. }
  157. return transformed;
  158. }
  159. // Transforms given set of `ranges` by given set of `deltas`. Returns transformed `ranges`.
  160. export function transformRangesByDeltas( ranges, deltas ) {
  161. for ( const delta of deltas ) {
  162. for ( const operation of delta.operations ) {
  163. // We look through all operations from all deltas.
  164. for ( let i = 0; i < ranges.length; i++ ) {
  165. // We transform every range by every operation.
  166. let result;
  167. switch ( operation.type ) {
  168. case 'insert':
  169. result = ranges[ i ]._getTransformedByInsertion(
  170. operation.position,
  171. operation.nodes.maxOffset,
  172. true
  173. );
  174. break;
  175. case 'move':
  176. case 'remove':
  177. case 'reinsert':
  178. result = ranges[ i ]._getTransformedByMove(
  179. operation.sourcePosition,
  180. operation.targetPosition,
  181. operation.howMany,
  182. true
  183. );
  184. break;
  185. }
  186. // If we have a transformation result, we substitute transformed range with it in `transformed` array.
  187. // Keep in mind that the result is an array and may contain multiple ranges.
  188. if ( result ) {
  189. ranges.splice( i, 1, ...result );
  190. // Fix iterator.
  191. i = i + result.length - 1;
  192. }
  193. }
  194. }
  195. }
  196. return ranges;
  197. }