8
0

transform.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 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. // Transform insert position by the other operation parameters.
  71. transformed.position = a.position.getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany, !isStrong );
  72. return [ transformed ];
  73. }
  74. },
  75. AttributeOperation: {
  76. // Transforms AttributeOperation `a` by InsertOperation `b`. Returns results as an array of operations.
  77. InsertOperation( a, b ) {
  78. // Transform this operation's range.
  79. const ranges = a.range.getTransformedByInsertion( b.position, b.nodeList.length );
  80. // Map transformed range(s) to operations and return them.
  81. return ranges.reverse().map( ( range ) => {
  82. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  83. } );
  84. },
  85. // Transforms AttributeOperation `a` by AttributeOperation `b`. Accepts a flag stating whether `a` is more important
  86. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  87. AttributeOperation( a, b, isStrong ) {
  88. if ( a.key === b.key ) {
  89. // If operations attributes are in conflict, check if their ranges intersect and manage them properly.
  90. let operations = [];
  91. // First, we want to apply change to the part of a range that has not been changed by the other operation.
  92. operations = operations.concat(
  93. a.range.getDifference( b.range ).map( ( range ) => {
  94. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  95. } )
  96. );
  97. if ( isStrong && !isEqual( a.newValue, b.newValue ) ) {
  98. // If this operation is more important, we want also want to apply change to the part of the
  99. // original range that has already been changed by the other operation. Since that range
  100. // got changed we have to update oldAttr.
  101. const common = a.range.getIntersection( b.range );
  102. if ( common !== null ) {
  103. operations.push( new AttributeOperation( common, b.key, b.oldValue, a.newValue, a.baseVersion ) );
  104. }
  105. }
  106. // If no operations has been added nothing should get updated, but since we need to return
  107. // an instance of Operation we add NoOperation to the array.
  108. if ( operations.length === 0 ) {
  109. operations.push( new NoOperation( a.baseVersion ) );
  110. }
  111. return operations;
  112. } else {
  113. // If operations don't conflict, simply return an array containing just a clone of this operation.
  114. return [ a.clone() ];
  115. }
  116. },
  117. // Transforms AttributeOperation `a` by MoveOperation `b`. Returns results as an array of operations.
  118. MoveOperation( a, b ) {
  119. // Convert MoveOperation properties into a range.
  120. const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  121. // Get target position from the state "after" nodes specified by MoveOperation are "detached".
  122. const newTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  123. // This will aggregate transformed ranges.
  124. let ranges = [];
  125. // Difference is a part of changed range that is modified by AttributeOperation but are not affected
  126. // by MoveOperation. This can be zero, one or two ranges (if moved range is inside changed range).
  127. // If two ranges were returned it means that rangeB was inside rangeA. We will cover rangeB later.
  128. // Right now we will make a simplification and join difference ranges and transform them as one.
  129. const difference = joinRanges( a.range.getDifference( rangeB ) );
  130. // Common is a range of nodes that is affected by MoveOperation. So it got moved to other place.
  131. const common = a.range.getIntersection( rangeB );
  132. if ( difference !== null ) {
  133. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  134. // Take the start and the end of the range and transform them by deletion of moved nodes.
  135. // Note that if rangeB was inside AttributeOperation range, only difference.end will be transformed.
  136. // This nicely covers the joining simplification we did in the previous step.
  137. difference.start = difference.start.getTransformedByDeletion( b.sourcePosition, b.howMany );
  138. difference.end = difference.end.getTransformedByDeletion( b.sourcePosition, b.howMany );
  139. // MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
  140. // Note that since we operate on transformed difference range, we should transform by
  141. // previously transformed target position.
  142. // Note that we do not use Position.getTransformedByMove on range boundaries because we need to
  143. // transform by insertion a range as a whole, since newTargetPosition might be inside that range.
  144. ranges = difference.getTransformedByInsertion( newTargetPosition, b.howMany, false ).reverse();
  145. }
  146. if ( common !== null ) {
  147. // Here we do not need to worry that newTargetPosition is inside moved range, because that
  148. // would mean that the MoveOperation targets into itself, and that is incorrect operation.
  149. // Instead, we calculate the new position of that part of original range.
  150. common.start = common.start._getCombined( b.sourcePosition, newTargetPosition );
  151. common.end = common.end._getCombined( b.sourcePosition, newTargetPosition );
  152. ranges.push( common );
  153. }
  154. // Map transformed range(s) to operations and return them.
  155. return ranges.map( ( range ) => {
  156. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  157. } );
  158. }
  159. },
  160. MoveOperation: {
  161. // Transforms MoveOperation `a` by InsertOperation `b`. Accepts a flag stating whether `a` is more important
  162. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  163. InsertOperation( a, b, isStrong ) {
  164. // Get target position from the state "after" nodes are inserted by InsertOperation.
  165. const newTargetPosition = a.targetPosition.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
  166. // Create range from MoveOperation properties and transform it by insertion as well.
  167. const rangeB = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  168. const ranges = rangeB.getTransformedByInsertion( b.position, b.nodeList.length, true );
  169. // Map transformed range(s) to operations and return them.
  170. return ranges.reverse().map( ( range ) => {
  171. return new MoveOperation(
  172. range.start,
  173. range.end.offset - range.start.offset,
  174. Position.createFromPosition( newTargetPosition ),
  175. a.baseVersion
  176. );
  177. } );
  178. },
  179. AttributeOperation: doNotUpdate,
  180. // Transforms MoveOperation `a` by MoveOperation `b`. Accepts a flag stating whether `a` is more important
  181. // than `b` when it comes to resolving conflicts. Returns results as an array of operations.
  182. MoveOperation( a, b, isStrong ) {
  183. // Special case when both move operations' target positions are inside nodes that are
  184. // being moved by the other move operation. So in other words, we move ranges into inside of each other.
  185. // This case can't be solved reasonably (on the other hand, it should not happen often).
  186. if ( moveTargetIntoMovedRange( a, b ) && moveTargetIntoMovedRange( b, a ) ) {
  187. // Instead of transforming operation, we return a reverse of the operation that we transform by.
  188. // So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
  189. return [ b.getReversed() ];
  190. }
  191. // Create ranges from MoveOperations properties.
  192. const rangeA = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  193. const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  194. // Special case when transformed range contains both the other operation's whole range and target.
  195. // In such case, operations are not really conflicting and we should leave transformed operation as it is.
  196. // Without this we would have 3 or 4 operations and the transformation result would probably be not intuitive.
  197. if ( rangeA.containsRange( rangeB ) && rangeA.containsPosition( b.targetPosition ) ) {
  198. return [ a.clone() ];
  199. }
  200. // Mirror situation for the case above - now transformed range is wholly contained in the other
  201. // operation's range and also targets to that range. Without this special treatment we would
  202. // transform this operation into NoOperation, but this would not be compatible with the result
  203. // generated by the special case above.
  204. else if ( rangeB.containsRange( rangeA ) && rangeB.containsPosition( a.targetPosition ) ) {
  205. return [
  206. new MoveOperation(
  207. a.sourcePosition._getCombined( b.sourcePosition, b.targetPosition ),
  208. a.howMany,
  209. a.targetPosition._getCombined( b.sourcePosition, b.targetPosition ),
  210. a.baseVersion
  211. )
  212. ];
  213. }
  214. // All the other non-special cases are treated by generic algorithm below.
  215. const differenceSet = rangeA.getDifference( rangeB );
  216. const common = rangeA.getIntersection( rangeB );
  217. // This will aggregate transformed ranges.
  218. let ranges = [];
  219. // Get target position from the state "after" nodes specified by other MoveOperation are "detached".
  220. const moveTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  221. // First, we take care of that part of the range that is only modified by transformed operation.
  222. for ( let i = 0; i < differenceSet.length; i++ ) {
  223. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  224. // Take the start and the end of the range and transform them by deletion of moved nodes.
  225. differenceSet[ i ].start = differenceSet[ i ].start.getTransformedByDeletion( b.sourcePosition, b.howMany );
  226. differenceSet[ i ].end = differenceSet[ i ].end.getTransformedByDeletion( b.sourcePosition, b.howMany );
  227. // MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
  228. // Note that since we operate on transformed difference range, we should transform by
  229. // previously transformed target position.
  230. // Note that we do not use Position.getTransformedByMove on range boundaries because we need to
  231. // transform by insertion a range as a whole, since newTargetPosition might be inside that range.
  232. ranges = ranges.concat( differenceSet[ i ].getTransformedByInsertion( moveTargetPosition, b.howMany, true ) );
  233. }
  234. // Then, we have to manage the common part of both move ranges.
  235. // If MoveOperations has common range it can be one of two:
  236. // * on the same tree level - it means that we move the same nodes into different places
  237. // * on deeper tree level - it means that we move nodes that are inside moved nodes
  238. // The operations are conflicting only if they try to move exactly same nodes, so only in the first case.
  239. // So, we will handle common range if it is "deeper" or if transformed operation is more important.
  240. let isDeeper = utils.compareArrays( b.sourcePosition.getParentPath(), a.sourcePosition.getParentPath() ) == 'PREFIX';
  241. if ( common !== null && ( isDeeper || isStrong ) ) {
  242. // Here we do not need to worry that newTargetPosition is inside moved range, because that
  243. // would mean that the MoveOperation targets into itself, and that is incorrect operation.
  244. // Instead, we calculate the new position of that part of original range.
  245. common.start = common.start._getCombined( b.sourcePosition, moveTargetPosition );
  246. common.end = common.end._getCombined( b.sourcePosition, moveTargetPosition );
  247. // We have to take care of proper range order.
  248. // Note that both push, splice and unshift do the same if there are no ranges in the array.
  249. if ( rangeB.end.isAfter( rangeA.end ) ) {
  250. ranges.push( common );
  251. } else if ( rangeB.start.isBefore( rangeA.start ) ) {
  252. ranges.unshift( common );
  253. } else {
  254. ranges.splice( 1, 0, common );
  255. }
  256. }
  257. // At this point we transformed this operation's source ranges it means that nothing should be changed.
  258. // But since we need to return an instance of Operation we return an array with NoOperation.
  259. if ( ranges.length === 0 ) {
  260. return [ new NoOperation( a.baseVersion ) ];
  261. }
  262. // Target position also could be affected by the other MoveOperation. We will transform it.
  263. let newTargetPosition = a.targetPosition.getTransformedByMove( b.sourcePosition, moveTargetPosition, b.howMany, !isStrong );
  264. // Map transformed range(s) to operations and return them.
  265. return ranges.reverse().map( ( range ) => {
  266. return new MoveOperation(
  267. range.start,
  268. range.end.offset - range.start.offset,
  269. newTargetPosition,
  270. a.baseVersion
  271. );
  272. } );
  273. }
  274. }
  275. };
  276. function transform( a, b, isStrong ) {
  277. let group;
  278. let algorithm;
  279. if ( a instanceof InsertOperation ) {
  280. group = ot.InsertOperation;
  281. } else if ( a instanceof AttributeOperation ) {
  282. group = ot.AttributeOperation;
  283. } else if ( a instanceof MoveOperation ) {
  284. group = ot.MoveOperation;
  285. } else {
  286. algorithm = doNotUpdate;
  287. }
  288. if ( group ) {
  289. if ( b instanceof InsertOperation ) {
  290. algorithm = group.InsertOperation;
  291. } else if ( b instanceof AttributeOperation ) {
  292. algorithm = group.AttributeOperation;
  293. } else if ( b instanceof MoveOperation ) {
  294. algorithm = group.MoveOperation;
  295. } else {
  296. algorithm = doNotUpdate;
  297. }
  298. }
  299. let transformed = algorithm( a, b, isStrong );
  300. return updateBaseVersions( a.baseVersion, transformed );
  301. }
  302. // When we don't want to update an operation, we create and return a clone of it.
  303. // Returns the operation in "unified format" - wrapped in an Array.
  304. function doNotUpdate( operation ) {
  305. return [ operation.clone() ];
  306. }
  307. // Takes an Array of operations and sets consecutive base versions for them, starting from given base version.
  308. // Returns the passed array.
  309. function updateBaseVersions( baseVersion, operations ) {
  310. for ( let i = 0; i < operations.length; i++ ) {
  311. operations[ i ].baseVersion = baseVersion + i + 1;
  312. }
  313. return operations;
  314. }
  315. // Checks whether MoveOperation targetPosition is inside a node from the moved range of the other MoveOperation.
  316. function moveTargetIntoMovedRange( a, b ) {
  317. return a.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany ) === null;
  318. }
  319. // Gets an array of Ranges and produces one Range out of it. The root of a new range will be same as
  320. // the root of the first range in the array. If any of given ranges has different root than the first range,
  321. // it will be discarded.
  322. function joinRanges( ranges ) {
  323. if ( ranges.length === 0 ) {
  324. return null;
  325. } else if ( ranges.length == 1 ) {
  326. return ranges[ 0 ];
  327. } else {
  328. ranges[ 0 ].end = ranges[ ranges.length - 1 ].end;
  329. return ranges[ 0 ];
  330. }
  331. }