8
0

transform.js 19 KB

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