8
0

transform.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import InsertOperation from './insertoperation.js';
  7. import AttributeOperation from './attributeoperation.js';
  8. import MoveOperation from './moveoperation.js';
  9. import RemoveOperation from './removeoperation.js';
  10. import NoOperation from './nooperation.js';
  11. import Range from '../range.js';
  12. import isEqual from '../../lib/lodash/isEqual.js';
  13. import utils from '../../utils.js';
  14. /**
  15. * Transforms given {@link core.treeModel.operation.Operation operation} by another {@link core.treeModel.operation.Operation operation} and
  16. * returns the result of that transformation as an array containing one or more {@link core.treeModel.operation.Operation operation}
  17. * elements.
  18. *
  19. * Operations work on specified positions, passed to them when they are created. Whenever {@link core.treeModel.Document document}
  20. * changes, we have to reflect those modifications by updating or "transforming" operations which are not yet applied.
  21. * When an operation is transformed, its parameters may change based on the operation by which it is transformed.
  22. * If the transform-by operation applied any modifications to the Tree Data Model which affect positions or nodes
  23. * connected with transformed operation, those changes will be reflected in the parameters of the returned operation(s).
  24. *
  25. * Whenever the {@link core.treeModel.Document document} has different {@link core.treeModel.Document#baseVersion}
  26. * than the operation you want to {@link core.treeModel.Document#applyOperation apply}, you need to transform that
  27. * operation by all operations which were already applied to the {@link core.treeModel.Document document} and have greater
  28. * {@link core.treeModel.Document#baseVersion} than the operation being applied. Transform them in the same order as those
  29. * operations which were applied. This way all modifications done to the Tree Data Model will be reflected
  30. * in the operation parameters and the operation will "operate" on "up-to-date" version of the Tree Data Model.
  31. * This is mostly the case with Operational Transformations but it might be needed in particular features as well.
  32. *
  33. * In some cases, when given operation apply changes to the same nodes as this operation, two or more operations need
  34. * to be created as one would not be able to reflect the combination of these operations.
  35. * This is why an array is returned instead of a single object. All returned operations have to be applied
  36. * (or further transformed) to get an effect which was intended in pre-transformed operation.
  37. *
  38. * Sometimes two operations are in conflict. This happens when they modify the same node in a different way, i.e.
  39. * set different value for the same attribute or move the node into different positions. When this happens,
  40. * we need to decide which operation is more important. We can't assume that operation `a` or operation `b` is always
  41. * more important. In Operational Transformations algorithms we often need to get a result of transforming
  42. * `a` by `b` and also `b` by `a`. In both transformations the same operation has to be the important one. If we assume
  43. * that first or the second passed operation is always more important we won't be able to solve this case.
  44. *
  45. * @external core.treeModel.operation
  46. * @function core.treeModel.operation.transform
  47. * @param {core.treeModel.operation.Operation} a Operation that will be transformed.
  48. * @param {core.treeModel.operation.Operation} b Operation to transform by.
  49. * @param {Boolean} isAMoreImportantThanB Flag indicating whether the operation which will be transformed (`a`) should be treated
  50. * as more important when resolving conflicts.
  51. * @returns {Array.<core.treeModel.operation.Operation>} Result of the transformation.
  52. */
  53. export default transform;
  54. const ot = {
  55. InsertOperation: {
  56. // Transforms InsertOperation `a` by InsertOperation `b`. Accepts a flag stating whether `a` is more important
  57. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  58. InsertOperation( a, b, isStrong ) {
  59. // Transformed operations are always new instances, not references to the original operations.
  60. const transformed = a.clone();
  61. // Transform insert position by the other operation position.
  62. transformed.position = transformed.position.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
  63. return [ transformed ];
  64. },
  65. AttributeOperation: doNotUpdate,
  66. // Transforms InsertOperation `a` by MoveOperation `b`. Accepts a flag stating whether `a` is more important
  67. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  68. MoveOperation( a, b, isStrong ) {
  69. const transformed = a.clone();
  70. const moveTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  71. // Transform insert position by the other operation parameters.
  72. transformed.position = a.position.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, !isStrong, b.isSticky );
  73. return [ transformed ];
  74. }
  75. },
  76. AttributeOperation: {
  77. // Transforms AttributeOperation `a` by InsertOperation `b`. Returns results as an array of operations.
  78. InsertOperation( a, b ) {
  79. // Transform this operation's range.
  80. const ranges = a.range.getTransformedByInsertion( b.position, b.nodeList.length, true, false );
  81. // Map transformed range(s) to operations and return them.
  82. return ranges.reverse().map( ( range ) => {
  83. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  84. } );
  85. },
  86. // Transforms AttributeOperation `a` by AttributeOperation `b`. Accepts a flag stating whether `a` is more important
  87. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  88. AttributeOperation( a, b, isStrong ) {
  89. if ( a.key === b.key ) {
  90. // If operations attributes are in conflict, check if their ranges intersect and manage them properly.
  91. // First, we want to apply change to the part of a range that has not been changed by the other operation.
  92. let operations = a.range.getDifference( b.range ).map( ( range ) => {
  93. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  94. } );
  95. // Then we take care of the common part of ranges, but only if operations has different `newValue`.
  96. if ( isStrong && !isEqual( a.newValue, b.newValue ) ) {
  97. // If this operation is more important, we also want to apply change to the part of the
  98. // original range that has already been changed by the other operation. Since that range
  99. // got changed we also have to update `oldValue`.
  100. const common = a.range.getIntersection( b.range );
  101. if ( common !== null ) {
  102. operations.push( new AttributeOperation( common, b.key, b.oldValue, a.newValue, a.baseVersion ) );
  103. }
  104. }
  105. // If no operations has been added nothing should get updated, but since we need to return
  106. // an instance of Operation we add NoOperation to the array.
  107. if ( operations.length === 0 ) {
  108. operations.push( new NoOperation( a.baseVersion ) );
  109. }
  110. return operations;
  111. } else {
  112. // If operations don't conflict, simply return an array containing just a clone of this operation.
  113. return [ a.clone() ];
  114. }
  115. },
  116. // Transforms AttributeOperation `a` by MoveOperation `b`. Returns results as an array of operations.
  117. MoveOperation( a, b ) {
  118. // Convert MoveOperation properties into a range.
  119. const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  120. // Get target position from the state "after" nodes specified by MoveOperation are "detached".
  121. const newTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  122. // This will aggregate transformed ranges.
  123. let ranges = [];
  124. // Difference is a part of changed range that is modified by AttributeOperation but is not affected
  125. // by MoveOperation. This can be zero, one or two ranges (if moved range is inside changed range).
  126. // Right now we will make a simplification and join difference ranges and transform them as one. We will cover rangeB later.
  127. const difference = joinRanges( a.range.getDifference( rangeB ) );
  128. // Common is a range of nodes that is affected by MoveOperation. So it got moved to other place.
  129. const common = a.range.getIntersection( rangeB );
  130. if ( difference !== null ) {
  131. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  132. // Take the start and the end of the range and transform them by deletion of moved nodes.
  133. // Note that if rangeB was inside AttributeOperation range, only difference.end will be transformed.
  134. // This nicely covers the joining simplification we did in the previous step.
  135. difference.start = difference.start.getTransformedByDeletion( b.sourcePosition, b.howMany );
  136. difference.end = difference.end.getTransformedByDeletion( b.sourcePosition, b.howMany );
  137. // MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
  138. // Note that since we operate on transformed difference range, we should transform by
  139. // previously transformed target position.
  140. // Note that we do not use Position.getTransformedByMove on range boundaries because we need to
  141. // transform by insertion a range as a whole, since newTargetPosition might be inside that range.
  142. ranges = difference.getTransformedByInsertion( newTargetPosition, b.howMany, true, false ).reverse();
  143. }
  144. if ( common !== null ) {
  145. // Here we do not need to worry that newTargetPosition is inside moved range, because that
  146. // would mean that the MoveOperation targets into itself, and that is incorrect operation.
  147. // Instead, we calculate the new position of that part of original range.
  148. common.start = common.start._getCombined( b.sourcePosition, newTargetPosition );
  149. common.end = common.end._getCombined( b.sourcePosition, newTargetPosition );
  150. ranges.push( common );
  151. }
  152. // Map transformed range(s) to operations and return them.
  153. return ranges.map( ( range ) => {
  154. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  155. } );
  156. }
  157. },
  158. MoveOperation: {
  159. // Transforms MoveOperation `a` by InsertOperation `b`. Accepts a flag stating whether `a` is more important
  160. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  161. InsertOperation( a, b, isStrong ) {
  162. // Create range from MoveOperation properties and transform it by insertion.
  163. let range = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  164. range = range.getTransformedByInsertion( b.position, b.nodeList.length, false, a.isSticky )[ 0 ];
  165. return [
  166. new a.constructor(
  167. range.start,
  168. range.end.offset - range.start.offset,
  169. a instanceof RemoveOperation ? a.baseVersion : a.targetPosition.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong ),
  170. a instanceof RemoveOperation ? undefined : a.baseVersion
  171. )
  172. ];
  173. },
  174. AttributeOperation: doNotUpdate,
  175. // Transforms MoveOperation `a` by MoveOperation `b`. Accepts a flag stating whether `a` is more important
  176. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  177. MoveOperation( a, b, isStrong ) {
  178. // Special case when both move operations' target positions are inside nodes that are
  179. // being moved by the other move operation. So in other words, we move ranges into inside of each other.
  180. // This case can't be solved reasonably (on the other hand, it should not happen often).
  181. if ( moveTargetIntoMovedRange( a, b ) && moveTargetIntoMovedRange( b, a ) ) {
  182. // Instead of transforming operation, we return a reverse of the operation that we transform by.
  183. // So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
  184. return [ b.getReversed() ];
  185. }
  186. // If one of operations is actually a remove operation, we force remove operation to be the "stronger" one
  187. // to provide more expected results.
  188. if ( a instanceof RemoveOperation && !( b instanceof RemoveOperation ) ) {
  189. isStrong = true;
  190. } else if ( !( a instanceof RemoveOperation ) && b instanceof RemoveOperation ) {
  191. isStrong = false;
  192. }
  193. let isSticky = a.isSticky && b.isSticky;
  194. // Create ranges from MoveOperations properties.
  195. const rangeA = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  196. const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  197. // Get target position from the state "after" nodes specified by other MoveOperation are "detached".
  198. const moveTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  199. // This will aggregate transformed ranges.
  200. let ranges = [];
  201. // All the other non-special cases are treated by generic algorithm below.
  202. let difference = joinRanges( rangeA.getDifference( rangeB ) );
  203. if ( difference ) {
  204. difference.start = difference.start.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, !isSticky, false );
  205. difference.end = difference.end.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, isSticky, false );
  206. ranges.push( difference );
  207. }
  208. // Then, we have to manage the common part of both move ranges.
  209. const common = rangeA.getIntersection( rangeB );
  210. // If MoveOperations has common range it can be one of two:
  211. // * on the same tree level - it means that we move the same nodes into different places
  212. // * on deeper tree level - it means that we move nodes that are inside moved nodes
  213. // The operations are conflicting only if they try to move exactly same nodes, so only in the first case.
  214. // So, we will handle common range if it is "deeper" or if transformed operation is more important.
  215. let isDeeper = utils.compareArrays( b.sourcePosition.getParentPath(), a.sourcePosition.getParentPath() ) == 'PREFIX';
  216. // If the `b` MoveOperation points inside the `a` MoveOperation range, the common part will be included in
  217. // range(s) that (is) are results of processing `difference`. If that's the case, we cannot include it again.
  218. let bIsIncluded = rangeA.containsPosition( b.targetPosition ) ||
  219. ( rangeA.start.isEqual( b.targetPosition ) && isSticky ) ||
  220. ( rangeA.end.isEqual( b.targetPosition ) && isSticky );
  221. // If the `b` MoveOperation range contains both whole `a` range and target position we do an exception and
  222. // transform `a` operation. Normally, when same nodes are moved, we stick with stronger operation's target.
  223. // Here it is a move inside larger range so there is no conflict because after all, all nodes from
  224. // smaller range will be moved to larger range target. The effect of this transformation feels natural.
  225. let aIsInside = rangeB.containsRange( rangeA ) && rangeB.containsPosition( a.targetPosition );
  226. if ( common !== null && ( isDeeper || isStrong || aIsInside ) && !bIsIncluded ) {
  227. // Here we do not need to worry that newTargetPosition is inside moved range, because that
  228. // would mean that the MoveOperation targets into itself, and that is incorrect operation.
  229. // Instead, we calculate the new position of that part of original range.
  230. common.start = common.start._getCombined( b.sourcePosition, moveTargetPosition );
  231. common.end = common.end._getCombined( b.sourcePosition, moveTargetPosition );
  232. // We have to take care of proper range order.
  233. if ( difference && difference.start.isBefore( common.start ) ) {
  234. ranges.push( common );
  235. } else {
  236. ranges.unshift( common );
  237. }
  238. }
  239. // At this point we transformed this operation's source ranges it means that nothing should be changed.
  240. // But since we need to return an instance of Operation we return an array with NoOperation.
  241. if ( ranges.length === 0 ) {
  242. return [ new NoOperation( a.baseVersion ) ];
  243. }
  244. // Target position also could be affected by the other MoveOperation. We will transform it.
  245. let newTargetPosition = a.targetPosition.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, !isStrong, isSticky );
  246. // Map transformed range(s) to operations and return them.
  247. return ranges.reverse().map( ( range ) => {
  248. // We want to keep correct operation class.
  249. return new a.constructor(
  250. range.start,
  251. range.end.offset - range.start.offset,
  252. a instanceof RemoveOperation ? a.baseVersion : newTargetPosition,
  253. a instanceof RemoveOperation ? undefined : a.baseVersion
  254. );
  255. } );
  256. }
  257. }
  258. };
  259. function transform( a, b, isStrong ) {
  260. let group;
  261. let algorithm;
  262. if ( a instanceof InsertOperation ) {
  263. group = ot.InsertOperation;
  264. } else if ( a instanceof AttributeOperation ) {
  265. group = ot.AttributeOperation;
  266. } else if ( a instanceof MoveOperation ) {
  267. group = ot.MoveOperation;
  268. } else {
  269. algorithm = doNotUpdate;
  270. }
  271. if ( group ) {
  272. if ( b instanceof InsertOperation ) {
  273. algorithm = group.InsertOperation;
  274. } else if ( b instanceof AttributeOperation ) {
  275. algorithm = group.AttributeOperation;
  276. } else if ( b instanceof MoveOperation ) {
  277. algorithm = group.MoveOperation;
  278. } else {
  279. algorithm = doNotUpdate;
  280. }
  281. }
  282. let transformed = algorithm( a, b, isStrong );
  283. return updateBaseVersions( a.baseVersion, transformed );
  284. }
  285. // When we don't want to update an operation, we create and return a clone of it.
  286. // Returns the operation in "unified format" - wrapped in an Array.
  287. function doNotUpdate( operation ) {
  288. return [ operation.clone() ];
  289. }
  290. // Takes an Array of operations and sets consecutive base versions for them, starting from given base version.
  291. // Returns the passed array.
  292. function updateBaseVersions( baseVersion, operations ) {
  293. for ( let i = 0; i < operations.length; i++ ) {
  294. operations[ i ].baseVersion = baseVersion + i + 1;
  295. }
  296. return operations;
  297. }
  298. // Checks whether MoveOperation targetPosition is inside a node from the moved range of the other MoveOperation.
  299. function moveTargetIntoMovedRange( a, b ) {
  300. return a.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany ) === null;
  301. }
  302. // Gets an array of Ranges and produces one Range out of it. The root of a new range will be same as
  303. // the root of the first range in the array. If any of given ranges has different root than the first range,
  304. // it will be discarded.
  305. function joinRanges( ranges ) {
  306. if ( ranges.length === 0 ) {
  307. return null;
  308. } else if ( ranges.length == 1 ) {
  309. return ranges[ 0 ];
  310. } else {
  311. ranges[ 0 ].end = ranges[ ranges.length - 1 ].end;
  312. return ranges[ 0 ];
  313. }
  314. }