transformoperation.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. /**
  7. * Transforms given {document.operation.Operation} by another {document.operation.Operation} and returns the result of
  8. * that transformation as an Array containing one or more {document.operation.Operation} elements.
  9. *
  10. * Operations operate on specified positions, passed to them when they are created. Whenever {@link document.Document document}
  11. * changes, we have to reflect those modifications by updating, or "transforming", operations (which are not yet applied).
  12. * When operation is transformed, its parameters may change basing on the operation by which it is transformed.
  13. * If the transform-by operation applied any modifications to the Tree Model that affects positions or nodes
  14. * connected with transformed operation, those changes will be reflected in the parameters of the returned operation(s).
  15. *
  16. * Whenever the {@link document.Document document} has different {@link document.Document#baseVersion}
  17. * than an operation you want to {@link document.Document#applyOperation apply}, you need to transform that
  18. * operation by all the operations that were applied to the {@link document.Document document} since it has
  19. * {@link document.Document#baseVersion} same as the operation. Transform them in the same order as those
  20. * operations were applied. This way all modifications done to the Tree Model will be reflected
  21. * in the operation parameters and the operation will "operate" on "up-to-date" version of the Tree Model.
  22. * This is mostly the case with Operational Transformation but it might be needed in particular features.
  23. *
  24. * In some cases, when given operation apply changes to the same nodes as this operation, there is a need
  25. * to create two operations as a result. It would be impossible to create just one operation that handles
  26. * modifications needed to be applied to the tree. This is why Array is returned instead of single object.
  27. * All returned operations has to be applied (or further transformed) to get an effect that was intended in
  28. * pre-transformed operation.
  29. *
  30. * @function transformOperation
  31. * @param {document.operation.Operation} a Operation that will be transformed.
  32. * @param {document.operation.Operation} b Operation to transform by.
  33. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  34. * when resolving conflicts.
  35. * @returns {Array.<document.operation.Operation>} Result of the transformation.
  36. */
  37. CKEDITOR.define( [
  38. 'document/operation/insertoperation',
  39. 'document/operation/changeoperation',
  40. 'document/operation/moveoperation',
  41. 'document/operation/nooperation',
  42. 'document/range',
  43. 'utils'
  44. ], ( InsertOperation, ChangeOperation, MoveOperation, NoOperation, Range, utils ) => {
  45. // When we don't want to update an operation, we create and return a clone of it.
  46. // Returns the operation in "unified format" - wrapped in an Array.
  47. function doNotUpdate( operation ) {
  48. return [ operation.clone() ];
  49. }
  50. // Takes an Array of operations and sets consecutive base versions for them, starting from given base version.
  51. // Returns the passed array.
  52. function updateBaseVersions( baseVersion, operations ) {
  53. for ( let i = 0; i < operations.length; i++ ) {
  54. operations[ i ].baseVersion = baseVersion + i + 1;
  55. }
  56. return operations;
  57. }
  58. // Checks whether MoveOperation targetPosition is inside a node from the moved range of the other MoveOperation.
  59. function moveTargetIntoMovedRange( a, b ) {
  60. return a.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany ) === null;
  61. }
  62. // Takes two ChangeOperations and checks whether their attributes are in conflict.
  63. // This happens when both operations changes an attribute with the same key and they either set different
  64. // values for this attribute or one of them removes it while the other one sets it.
  65. // Returns true if attributes are in conflict.
  66. function haveConflictingAttributes( a, b ) {
  67. // Keeping in mind that newAttr or oldAttr might be null.
  68. // We will retrieve the key from whichever parameter is set.
  69. const keyA = ( a.newAttr || a.oldAttr ).key;
  70. const keyB = ( b.newAttr || b.oldAttr ).key;
  71. if ( keyA != keyB ) {
  72. // Different keys - not conflicting.
  73. return false;
  74. }
  75. // Check if they set different value or one of them removes the attribute.
  76. return ( a.newAttr === null && b.newAttr !== null ) ||
  77. ( a.newAttr !== null && b.newAttr === null ) ||
  78. ( !a.newAttr.isEqual( b.newAttr ) );
  79. }
  80. const ot = {
  81. InsertOperation: {
  82. /**
  83. * Returns an array containing the result of transforming
  84. * {document.operation.InsertOperation} by {document.operation.InsertOperation}.
  85. *
  86. * @param {document.operation.InsertOperation} a Operation that will be transformed.
  87. * @param {document.operation.InsertOperation} b Operation to transform by.
  88. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  89. * when resolving conflicts.
  90. * @returns {Array.<document.operation.InsertOperation>} Result of the transformation.
  91. */
  92. InsertOperation( a, b, isStrong ) {
  93. // Transformed operations are always new instances, not references to the original operations.
  94. const transformed = a.clone();
  95. // Transform operation position by the other operation position.
  96. transformed.position = transformed.position.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
  97. return [ transformed ];
  98. },
  99. ChangeOperation: doNotUpdate,
  100. /**
  101. * Returns an array containing the result of transforming
  102. * {document.operation.InsertOperation} by {document.operation.MoveOperation}.
  103. *
  104. * @param {document.operation.InsertOperation} a Operation that will be transformed.
  105. * @param {document.operation.MoveOperation} b Operation to transform by.
  106. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  107. * when resolving conflicts.
  108. * @returns {Array.<document.operation.InsertOperation>} Result of the transformation.
  109. */
  110. MoveOperation( a, b, isStrong ) {
  111. const transformed = a.clone();
  112. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  113. const newPosition = a.position.getTransformedByDeletion( b.sourcePosition, b.howMany );
  114. if ( newPosition === null ) {
  115. // This operation's position was inside a node moved by MoveOperation. We substitute that position by
  116. // the combination of move target position and insert position. This reflects changes done by MoveOperation.
  117. transformed.position = transformed.position.getCombined( b.sourcePosition, b.targetPosition );
  118. } else {
  119. // Here we have the insert position after some nodes has been removed by MoveOperation.
  120. // Next step is to reflect pasting nodes by MoveOperation, which might further affect the position.
  121. transformed.position = newPosition.getTransformedByInsertion( b.targetPosition, b.howMany, !isStrong );
  122. }
  123. return [ transformed ];
  124. }
  125. },
  126. ChangeOperation: {
  127. /**
  128. * Returns an array containing the result of transforming
  129. * {document.operation.ChangeOperation} by {document.operation.InsertOperation}.
  130. *
  131. * @param {document.operation.ChangeOperation} a Operation that will be transformed.
  132. * @param {document.operation.InsertOperation} b Operation to transform by.
  133. * @returns {Array.<document.operation.ChangeOperation>} Result of the transformation.
  134. */
  135. InsertOperation( a, b ) {
  136. // Transform this operation's range.
  137. const ranges = a.range.getTransformedByInsertion( b.position, b.nodeList.length );
  138. // Map transformed range(s) to operations and return them.
  139. return ranges.map( ( range ) => {
  140. return new ChangeOperation(
  141. range,
  142. a.oldAttr,
  143. a.newAttr,
  144. a.baseVersion
  145. );
  146. } );
  147. },
  148. /**
  149. * Returns an array containing the result of transforming
  150. * {document.operation.ChangeOperation} by {document.operation.ChangeOperation}.
  151. *
  152. * @param {document.operation.ChangeOperation} a Operation that will be transformed.
  153. * @param {document.operation.ChangeOperation} b Operation to transform by.
  154. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  155. * when resolving conflicts.
  156. * @returns {Array.<document.operation.ChangeOperation>} Result of the transformation.
  157. */
  158. ChangeOperation( a, b, isStrong ) {
  159. if ( !isStrong && haveConflictingAttributes( a, b ) ) {
  160. // If operations' attributes are in conflict and this operation is less important
  161. // we have to check if operations' ranges intersect and manage them properly.
  162. // We get the range(s) which are only affected by this operation.
  163. const ranges = a.range.getDifference( b.range );
  164. if ( ranges.length === 0 ) {
  165. // If there are no such ranges, this operation should not do anything (as it is less important).
  166. return [ new NoOperation( a.baseVersion ) ];
  167. } else {
  168. // If there are such ranges, map them to operations and then return.
  169. return ranges.map( ( range ) => {
  170. return new ChangeOperation(
  171. range,
  172. a.oldAttr,
  173. a.newAttr,
  174. a.baseVersion
  175. );
  176. } );
  177. }
  178. } else {
  179. // If operations don't conflict or this operation is more important
  180. // simply, return an array containing just a clone of this operation.
  181. return [ a.clone() ];
  182. }
  183. },
  184. /**
  185. * Returns an array containing the result of transforming
  186. * {document.operation.ChangeOperation} by {document.operation.MoveOperation}.
  187. *
  188. * @param {document.operation.ChangeOperation} a Operation that will be transformed.
  189. * @param {document.operation.MoveOperation} b Operation to transform by.
  190. * @returns {Array.<document.operation.ChangeOperation>} Result of the transformation.
  191. */
  192. MoveOperation( a, b ) {
  193. // Convert MoveOperation properties into a range.
  194. const rangeB = Range.createFromPositionAndOffset( b.sourcePosition, b.howMany );
  195. // Get target position from the state "after" nodes specified by MoveOperation are "detached".
  196. const newTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  197. // This will aggregate transformed ranges.
  198. let ranges = [];
  199. const differenceSet = a.range.getDifference( rangeB );
  200. const common = a.range.getIntersection( rangeB );
  201. // Difference is a part of changed range that is modified by ChangeOperation but are not affected
  202. // by MoveOperation. This can be zero, one or two ranges (if moved range is inside changed range).
  203. if ( differenceSet.length > 0 ) {
  204. const difference = differenceSet[ 0 ];
  205. // If two ranges were returned it means that rangeB was inside rangeA. We will cover rangeB later.
  206. // Right now we will make a simplification and join difference ranges and transform them as one.
  207. if ( differenceSet.length == 2 ) {
  208. difference.end = differenceSet[ 1 ].end.clone();
  209. }
  210. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  211. // Take the start and the end of the range and transform them by deletion of moved nodes.
  212. // Note that if rangeB was inside ChangeOperation range, only difference.end will be transformed.
  213. // This nicely covers the joining simplification we did in the previous step.
  214. difference.start = difference.start.getTransformedByDeletion( b.sourcePosition, b.howMany );
  215. difference.end = difference.end.getTransformedByDeletion( b.sourcePosition, b.howMany );
  216. // MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
  217. // Note that since we operate on transformed difference range, we should transform by
  218. // previously transformed target position.
  219. ranges = difference.getTransformedByInsertion( newTargetPosition, b.howMany, false );
  220. }
  221. // Common is a range of nodes that is affected by MoveOperation. So it got moved to other place.
  222. if ( common !== null ) {
  223. // We substitute original position by the combination of target position and original position.
  224. // This reflects that those nodes were moved to another place by MoveOperation.
  225. common.start = common.start.getCombined( b.sourcePosition, newTargetPosition );
  226. common.end = common.end.getCombined( b.sourcePosition, newTargetPosition );
  227. ranges.push( common );
  228. }
  229. // Map transformed range(s) to operations and return them.
  230. return ranges.map( ( range ) => {
  231. return new ChangeOperation(
  232. range,
  233. a.oldAttr,
  234. a.newAttr,
  235. a.baseVersion
  236. );
  237. } );
  238. }
  239. },
  240. MoveOperation: {
  241. /**
  242. * Returns an array containing the result of transforming
  243. * {document.operation.MoveOperation} by {document.operation.InsertOperation}.
  244. *
  245. * @param {document.operation.MoveOperation} a Operation that will be transformed.
  246. * @param {document.operation.InsertOperation} b Operation to transform by.
  247. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  248. * when resolving conflicts.
  249. * @returns {Array.<document.operation.MoveOperation>} Result of the transformation.
  250. */
  251. InsertOperation( a, b, isStrong ) {
  252. // Get target position from the state "after" nodes are inserted by InsertOperation.
  253. const newTargetPosition = a.targetPosition.getTransformedByInsertion( b.position, b.nodeList.length, !isStrong );
  254. // Create range from MoveOperation properties and transform it by insertion as well.
  255. const rangeB = Range.createFromPositionAndOffset( a.sourcePosition, a.howMany );
  256. const ranges = rangeB.getTransformedByInsertion( b.position, b.nodeList.length, true );
  257. // Map transformed range(s) to operations and return them.
  258. return ranges.map( ( range ) => {
  259. return new MoveOperation(
  260. range.start,
  261. newTargetPosition.clone(),
  262. range.end.offset - range.start.offset,
  263. a.baseVersion
  264. );
  265. } );
  266. },
  267. ChangeOperation: doNotUpdate,
  268. /**
  269. * Returns an array containing the result of transforming
  270. * {document.operation.MoveOperation} by {document.operation.MoveOperation}.
  271. *
  272. * @param {document.operation.MoveOperation} a Operation that will be transformed.
  273. * @param {document.operation.MoveOperation} b Operation to transform by.
  274. * @param {Boolean} isStrong Flag indicating whether this operation should be treated as more important
  275. * when resolving conflicts.
  276. * @returns {Array.<document.operation.MoveOperation>} Result of the transformation.
  277. */
  278. MoveOperation( a, b, isStrong ) {
  279. // There is a special case when both move operations' target positions are inside nodes that are
  280. // being moved by the other move operation. So in other words, we move ranges into inside of each other.
  281. // This case can't be solved reasonably (on the other hand, it should not happen often).
  282. if ( moveTargetIntoMovedRange( a, b ) && moveTargetIntoMovedRange( b, a ) ) {
  283. // Instead of transforming operation, we return a reverse of the operation that we transform by.
  284. // So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
  285. return [ b.getReversed() ];
  286. }
  287. // Get target position from the state "after" nodes specified by other MoveOperation are "detached".
  288. const moveTargetPosition = b.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  289. // This will aggregate transformed ranges.
  290. let ranges = [];
  291. // Create ranges from MoveOperations properties.
  292. const rangeA = Range.createFromPositionAndOffset( a.sourcePosition, a.howMany );
  293. const rangeB = Range.createFromPositionAndOffset( b.sourcePosition, b.howMany );
  294. const differenceSet = rangeA.getDifference( rangeB );
  295. // MoveOperations ranges may intersect.
  296. // First, we take care of that part of the range that is only modified by transformed operation.
  297. if ( differenceSet.length > 0 ) {
  298. const difference = differenceSet[ 0 ];
  299. // If two ranges were returned it means that rangeB was inside rangeA. We will cover rangeB later.
  300. // Right now we will make a simplification and join difference ranges and transform them as one.
  301. if ( differenceSet.length == 2 ) {
  302. difference.end = differenceSet[ 1 ].end.clone();
  303. }
  304. // MoveOperation removes nodes from their original position. We acknowledge this by proper transformation.
  305. // Take the start and the end of the range and transform them by deletion of moved nodes.
  306. // Note that if rangeB was inside rangeA, only difference.end will be transformed.
  307. // This nicely covers the joining simplification we did in the previous step.
  308. difference.start = difference.start.getTransformedByDeletion( b.sourcePosition, b.howMany );
  309. difference.end = difference.end.getTransformedByDeletion( b.sourcePosition, b.howMany );
  310. // MoveOperation pastes nodes into target position. We acknowledge this by proper transformation.
  311. // Note that since we operate on transformed difference range, we should transform by
  312. // previously transformed target position.
  313. ranges = difference.getTransformedByInsertion( moveTargetPosition, b.howMany, true );
  314. }
  315. // Then, we have to manage the common part of both move ranges.
  316. // If MoveOperations has common range it can be one of two:
  317. // * on the same tree level - it means that we move the same nodes into different places
  318. // * on deeper tree level - it means that we move nodes that are inside moved nodes
  319. // The operations are conflicting only if they try to move exactly same nodes, so only in the first case.
  320. // So, we will handle common range if it is "deeper" or if transformed operation is more important.
  321. if ( utils.compareArrays( b.sourcePosition.parentPath, a.sourcePosition.parentPath ) == utils.compareArrays.PREFIX || isStrong ) {
  322. const common = rangeA.getCommon( rangeB );
  323. if ( common !== null ) {
  324. // We substitute original position by the combination of target position and original position.
  325. // This reflects that those nodes were moved to another place by MoveOperation.
  326. common.start = common.start.getCombined( b.sourcePosition, moveTargetPosition );
  327. common.end = common.end.getCombined( b.sourcePosition, moveTargetPosition );
  328. ranges.push( common );
  329. }
  330. }
  331. // At this point we transformed this operation's source range. Now, we need to transform target position.
  332. // First, transform target position by deletion of the other operation's range.
  333. let newTargetPosition = a.targetPosition.getTransformedByDeletion( b.sourcePosition, b.howMany );
  334. if ( newTargetPosition === null ) {
  335. // Transformed operation target position was inside a node moved by the other MoveOperation.
  336. // We substitute that position by the combination of the other move target position and
  337. // transformed operation target position. This reflects changes done by the other MoveOperation.
  338. newTargetPosition = a.targetPosition.getCombined( b.sourcePosition, moveTargetPosition );
  339. } else {
  340. // Here we have transformed operation target position after some nodes has been removed by MoveOperation.
  341. // Next step is to reflect pasting nodes by MoveOperation, which might further affect the position.
  342. newTargetPosition = newTargetPosition.getTransformedByInsertion( moveTargetPosition, b.howMany, true );
  343. }
  344. // If we haven't got any ranges this far it means that both operations tried to move the same nodes and
  345. // transformed operation is less important. We return NoOperation in this case.
  346. if ( ranges.length === 0 ) {
  347. return [ new NoOperation( a.baseVersion ) ];
  348. }
  349. // At this point we might have multiple ranges. All ranges will be moved to the same, newTargetPosition.
  350. // To keep them in the right order, we need to move them starting from the last one.
  351. // [|ABC||DEF||GHI|] ==> [^], [|ABC||DEF|] ==> [^GHI], [|ABC|] ==> [^DEFGHI], [] ==> [ABCDEFGHI]
  352. // To achieve this, we sort ranges by their starting position in descending order.
  353. ranges.sort( ( a, b ) => a.start.isBefore( b.start ) ? 1 : -1 );
  354. // Map transformed range(s) to operations and return them.
  355. return ranges.map( ( range ) => {
  356. return new MoveOperation(
  357. range.start,
  358. newTargetPosition,
  359. range.end.offset - range.start.offset,
  360. a.baseVersion
  361. );
  362. } );
  363. }
  364. }
  365. };
  366. return ( a, b, isStrong ) => {
  367. let group;
  368. let algorithm;
  369. if ( a instanceof InsertOperation ) {
  370. group = ot.InsertOperation;
  371. } else if ( a instanceof ChangeOperation ) {
  372. group = ot.ChangeOperation;
  373. } else if ( a instanceof MoveOperation ) {
  374. group = ot.MoveOperation
  375. } else {
  376. algorithm = doNotUpdate;
  377. }
  378. if ( group ) {
  379. if ( b instanceof InsertOperation ) {
  380. algorithm = group.InsertOperation;
  381. } else if ( b instanceof ChangeOperation ) {
  382. algorithm = group.ChangeOperation;
  383. } else if ( b instanceof MoveOperation ) {
  384. algorithm = group.MoveOperation
  385. } else {
  386. algorithm = doNotUpdate;
  387. }
  388. }
  389. let transformed = algorithm( a, b, isStrong );
  390. return updateBaseVersions( a.baseVersion, transformed );
  391. };
  392. } );