transform.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805
  1. import InsertOperation from './insertoperation';
  2. import AttributeOperation from './attributeoperation';
  3. import RenameOperation from './renameoperation';
  4. import MarkerOperation from './markeroperation';
  5. import MoveOperation from './moveoperation';
  6. import RootAttributeOperation from './rootattributeoperation';
  7. import MergeOperation from './mergeoperation';
  8. import SplitOperation from './splitoperation';
  9. import WrapOperation from './wrapoperation';
  10. import UnwrapOperation from './unwrapoperation';
  11. import NoOperation from './nooperation';
  12. import Range from '../range';
  13. import Position from '../position';
  14. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  15. import log from '@ckeditor/ckeditor5-utils/src/log';
  16. const transformations = new Map();
  17. /**
  18. * @module engine/model/operation/transform
  19. */
  20. /**
  21. * Sets a transformation function to be be used to transform instances of class `OperationA` by instances of class `OperationB`.
  22. *
  23. * The `transformationFunction` is passed three parameters:
  24. *
  25. * * `a` - operation to be transformed, an instance of `OperationA`,
  26. * * `b` - operation to be transformed by, an instance of `OperationB`,
  27. * * {@link module:engine/model/operation/transform~TransformationContext `context`} - object with additional information about
  28. * transformation context.
  29. *
  30. * The `transformationFunction` should return transformation result, which is an array with one or multiple
  31. * {@link module:engine/model/operation/operation~Operation operation} instances.
  32. *
  33. * @protected
  34. * @param {Function} OperationA
  35. * @param {Function} OperationB
  36. * @param {Function} transformationFunction Function to use for transforming.
  37. */
  38. function setTransformation( OperationA, OperationB, transformationFunction ) {
  39. let aGroup = transformations.get( OperationA );
  40. if ( !aGroup ) {
  41. aGroup = new Map();
  42. transformations.set( OperationA, aGroup );
  43. }
  44. aGroup.set( OperationB, transformationFunction );
  45. }
  46. /**
  47. * Returns a previously set transformation function for transforming an instance of `OperationA` by an instance of `OperationB`.
  48. *
  49. * If no transformation was set for given pair of operations, {@link module:engine/model/operation/transform~noUpdateTransformation}
  50. * is returned. This means that if no transformation was set, the `OperationA` instance will not change when transformed
  51. * by the `OperationB` instance.
  52. *
  53. * @private
  54. * @param {Function} OperationA
  55. * @param {Function} OperationB
  56. * @returns {Function} Function set to transform an instance of `OperationA` by an instance of `OperationB`.
  57. */
  58. function getTransformation( OperationA, OperationB ) {
  59. const aGroup = transformations.get( OperationA );
  60. if ( aGroup && aGroup.has( OperationB ) ) {
  61. return aGroup.get( OperationB );
  62. }
  63. return noUpdateTransformation;
  64. }
  65. /**
  66. * A transformation function that only clones operation to transform, without changing it.
  67. *
  68. * @private
  69. * @param {module:engine/model/operation/operation~Operation} a Operation to transform.
  70. * @returns {Array.<module:engine/model/operation/operation~Operation>}
  71. */
  72. function noUpdateTransformation( a ) {
  73. return [ a ];
  74. }
  75. /**
  76. * Transforms operation `a` by operation `b`.
  77. *
  78. * @param {module:engine/model/operation/operation~Operation} a Operation to be transformed.
  79. * @param {module:engine/model/operation/operation~Operation} b Operation to transform by.
  80. * @param {module:engine/model/operation/transform~TransformationContext} context Transformation context for this transformation.
  81. * @returns {Array.<module:engine/model/operation/operation~Operation>} Transformation result.
  82. */
  83. export function transform( a, b, context = {} ) {
  84. const transformationFunction = getTransformation( a.constructor, b.constructor );
  85. try {
  86. a = a.clone();
  87. return transformationFunction( a, b, context );
  88. } catch ( e ) {
  89. log.error( 'Error during operation transformation!', e.message );
  90. log.error( 'Transformed operation', a );
  91. log.error( 'Operation transformed by', b );
  92. log.error( 'context.aIsStrong', context.aIsStrong );
  93. log.error( 'context.aWasUndone', context.aWasUndone );
  94. log.error( 'context.bWasUndone', context.bWasUndone );
  95. log.error( 'context.abRelation', context.abRelation );
  96. log.error( 'context.baRelation', context.baRelation );
  97. throw e;
  98. }
  99. }
  100. /**
  101. * Performs a transformation of two sets of operations - `operationsA` and `operationsB`. The transformation is two-way -
  102. * both transformed `operationsA` and transformed `operationsB` are returned.
  103. *
  104. * Note, that the first operation in each set should base on the same document state (
  105. * {@link module:engine/model/document~Document#version document version}).
  106. *
  107. * It is assumed that `operationsA` are "more important" during conflict resolution between two operations.
  108. *
  109. * New copies of both passed arrays and operations inside them are returned. Passed arguments are not altered.
  110. *
  111. * Base versions of the transformed operations sets are updated accordingly. For example, assume that base versions are `4`
  112. * and there are `3` operations in `operationsA` and `5` operations in `operationsB`. Then:
  113. *
  114. * * transformed `operationsA` will start from base version `9` (`4` base version + `5` operations B),
  115. * * transformed `operationsB` will start from base version `7` (`4` base version + `3` operations A).
  116. *
  117. * If no operation was broken into two during transformation, then both sets will end up with an operation that bases on version `11`:
  118. *
  119. * * transformed `operationsA` start from `9` and there are `3` of them, so the last will have `baseVersion` equal to `11`,
  120. * * transformed `operationsB` start from `7` and there are `5` of them, so the last will have `baseVersion` equal to `11`.
  121. *
  122. * @param {Array.<module:engine/model/operation/operation~Operation>} operationsA
  123. * @param {Array.<module:engine/model/operation/operation~Operation>} operationsB
  124. * @param {Object} options Additional transformation options.
  125. * @param {module:engine/model/document~Document|null} options.document Document which the operations change.
  126. * @param {Boolean} [options.useContext=false] Whether during transformation additional context information should be gathered and used.
  127. * @param {Boolean} [options.padWithNoOps=false] Whether additional {@link module:engine/model/operation/nooperation~NoOperation}s
  128. * should be added to the transformation results to force the same last base version for both transformed sets (in case
  129. * if some operations got broken into multiple operations during transformation).
  130. * @returns {Object} Transformation result.
  131. * @returns {Array.<module:engine/model/operation/operation~Operation>} return.operationsA Transformed `operationsA`.
  132. * @returns {Array.<module:engine/model/operation/operation~Operation>} return.operationsB Transformed `operationsB`.
  133. */
  134. export function transformSets( operationsA, operationsB, options ) {
  135. // Create new arrays so the originally passed arguments are not changed.
  136. // No need to clone operations, they are cloned as they are transformed.
  137. operationsA = operationsA.slice();
  138. operationsB = operationsB.slice();
  139. // If one of sets is empty there is simply nothing to transform, so return sets as they are.
  140. if ( operationsA.length == 0 || operationsB.length == 0 ) {
  141. return { operationsA, operationsB };
  142. }
  143. //
  144. // Following is a description of transformation process:
  145. //
  146. // There are `operationsA` and `operationsB` to be transformed, both by both.
  147. //
  148. // So, suppose we have sets of two operations each: `operationsA` = `[ a1, a2 ]`, `operationsB` = `[ b1, b2 ]`.
  149. //
  150. // Remember, that we can only transform operations that base on the same context. We assert that `a1` and `b1` base on
  151. // the same context and we transform them. Then, we get `a1'` and `b1'`. `a2` bases on a context with `a1` -- `a2`
  152. // is an operation that followed `a1`. Similarly, `b2` bases on a context with `b1`.
  153. //
  154. // However, since `a1'` is a result of transformation by `b1`, `a1'` now also has a context with `b1`. This means that
  155. // we can safely transform `a1'` by `b2`. As we finish transforming `a1`, we also transformed all `operationsB`.
  156. // All `operationsB` also have context including `a1`. Now, we can properly transform `a2` by those operations.
  157. //
  158. // The transformation process can be visualized on a transformation diagram ("diamond diagram"):
  159. //
  160. // [the initial state]
  161. // [common for a1 and b1]
  162. //
  163. // *
  164. // / \
  165. // / \
  166. // b1 a1
  167. // / \
  168. // / \
  169. // * *
  170. // / \ / \
  171. // / \ / \
  172. // b2 a1' b1' a2
  173. // / \ / \
  174. // / \ / \
  175. // * * *
  176. // \ / \ /
  177. // \ / \ /
  178. // a1'' b2' a2' b1''
  179. // \ / \ /
  180. // \ / \ /
  181. // * *
  182. // \ /
  183. // \ /
  184. // a2'' b2''
  185. // \ /
  186. // \ /
  187. // *
  188. //
  189. // [the final state]
  190. //
  191. // The final state can be reached from the initial state by applying `a1`, `a2`, `b1''` and `b2''`, as well as by
  192. // applying `b1`, `b2`, `a1''`, `a2''`. Note how the operations get to a proper common state before each pair is
  193. // transformed.
  194. //
  195. // Another thing to consider is that an operation during transformation can be broken into multiple operations.
  196. // Suppose that `a1` * `b1` = `[ a11', a12' ]` (instead of `a1'` that we considered previously).
  197. //
  198. // In that case, we leave `a12'` for later and we continue transforming `a11'` until it is transformed by all `operationsB`
  199. // (in our case it is just `b2`). At this point, `b1` is transformed by "whole" `a1`, while `b2` is only transformed
  200. // by `a11'`. Similarly, `a12'` is only transformed by `b1`. This leads to a conclusion that we need to start transforming `a12'`
  201. // from the moment just after it was broken. So, `a12'` is transformed by `b2`. Now, "the whole" `a1` is transformed
  202. // by `operationsB`, while all `operationsB` are transformed by "the whole" `a1`. This means that we can continue with
  203. // following `operationsA` (in our case it is just `a2`).
  204. //
  205. // Of course, also `operationsB` can be broken. However, since we focus on transforming operation `a` to the end,
  206. // the only thing to do is to store both pieces of operation `b`, so that the next transformed operation `a` will
  207. // be transformed by both of them.
  208. //
  209. // *
  210. // / \
  211. // / \
  212. // / \
  213. // b1 a1
  214. // / \
  215. // / \
  216. // / \
  217. // * *
  218. // / \ / \
  219. // / a11' / \
  220. // / \ / \
  221. // b2 * b1' a2
  222. // / / \ / \
  223. // / / a12' / \
  224. // / / \ / \
  225. // * b2' * *
  226. // \ / / \ /
  227. // a11'' / b21'' \ /
  228. // \ / / \ /
  229. // * * a2' b1''
  230. // \ / \ \ /
  231. // a12'' b22''\ \ /
  232. // \ / \ \ /
  233. // * a2'' *
  234. // \ \ /
  235. // \ \ b21'''
  236. // \ \ /
  237. // a2''' *
  238. // \ /
  239. // \ b22'''
  240. // \ /
  241. // *
  242. //
  243. // Note, how `a1` is broken and transformed into `a11'` and `a12'`, while `b2'` got broken and transformed into `b21''` and `b22''`.
  244. //
  245. // Having all that on mind, here is an outline for the transformation process algorithm:
  246. //
  247. // 1. We have `operationsA` and `operationsB` array, which we dynamically update as the transformation process goes.
  248. //
  249. // 2. We take next (or first) operation from `operationsA` and check from which operation `b` we need to start transforming it.
  250. // All original `operationsA` are set to be transformed starting from the first operation `b`.
  251. //
  252. // 3. We take operations from `operationsB`, one by one, starting from the correct one, and transform operation `a`
  253. // by operation `b` (and vice versa). We update `operationsA` and `operationsB` by replacing the original operations
  254. // with the transformation results.
  255. //
  256. // 4. If operation is broken into multiple operations, we save all the new operations in the place of the
  257. // original operation.
  258. //
  259. // 5. Additionally, if operation `a` was broken, for the "new" operation, we remember from which operation `b` it should
  260. // be transformed by.
  261. //
  262. // 6. We continue transforming "current" operation `a` until it is transformed by all `operationsB`. Then, go to 2.
  263. // unless the last operation `a` was transformed.
  264. //
  265. // The actual implementation of the above algorithm is slightly different, as only one loop (while) is used.
  266. // The difference is that we have "current" `a` operation to transform and we store the index of the next `b` operation
  267. // to transform by. Each loop operates on two indexes then: index pointing to currently processed `a` operation and
  268. // index pointing to next `b` operation. Each loop is just one `a * b` + `b * a` transformation. After each loop
  269. // operation `b` index is updated. If all `b` operations were visited for the current `a` operation, we change
  270. // current `a` operation index to the next one.
  271. //
  272. // For each operation `a`, keeps information what is the index in `operationsB` from which the transformation should start.
  273. const nextTransformIndex = new WeakMap();
  274. // For all the original `operationsA`, set that they should be transformed starting from the first of `operationsB`.
  275. for ( const op of operationsA ) {
  276. nextTransformIndex.set( op, 0 );
  277. }
  278. // Additional data that is used for some postprocessing after the main transformation process is done.
  279. const data = {
  280. nextBaseVersionA: operationsA[ operationsA.length - 1 ].baseVersion + 1,
  281. nextBaseVersionB: operationsB[ operationsB.length - 1 ].baseVersion + 1,
  282. originalOperationsACount: operationsA.length,
  283. originalOperationsBCount: operationsB.length
  284. };
  285. const contextFactory = new ContextFactory( options.document, options.useContext );
  286. contextFactory.setOriginalOperations( operationsA );
  287. contextFactory.setOriginalOperations( operationsB );
  288. // Index of currently transformed operation `a`.
  289. let i = 0;
  290. // While not all `operationsA` are transformed...
  291. while ( i < operationsA.length ) {
  292. // Get "current" operation `a`.
  293. const opA = operationsA[ i ];
  294. // For the "current" operation `a`, get the index of the next operation `b` to transform by.
  295. const indexB = nextTransformIndex.get( opA );
  296. // If operation `a` was already transformed by every operation `b`, change "current" operation `a` to the next one.
  297. if ( indexB == operationsB.length ) {
  298. i++;
  299. continue;
  300. }
  301. const opB = operationsB[ indexB ];
  302. // Transform `a` by `b` and `b` by `a`.
  303. const newOpsA = transform( opA, opB, contextFactory.getContext( opA, opB, true ) );
  304. const newOpsB = transform( opB, opA, contextFactory.getContext( opB, opA, false ) );
  305. // As a result we get one or more `newOpsA` and one or more `newOpsB` operations.
  306. // Update contextual information about operations.
  307. contextFactory.updateRelation( opA, opB );
  308. contextFactory.setOriginalOperations( newOpsA, opA );
  309. contextFactory.setOriginalOperations( newOpsB, opB );
  310. // For new `a` operations, update their index of the next operation `b` to transform them by.
  311. //
  312. // This is needed even if there was only one result (`a` was not broken) because that information is used
  313. // at the beginning of this loop every time.
  314. for ( const newOpA of newOpsA ) {
  315. // Acknowledge, that operation `b` also might be broken into multiple operations.
  316. //
  317. // This is why we raise `indexB` not just by 1. If `newOpsB` are multiple operations, they will be
  318. // spliced in the place of `opB`. So we need to change `transformBy` accordingly, so that an operation won't
  319. // be transformed by the same operation (part of it) again.
  320. nextTransformIndex.set( newOpA, indexB + newOpsB.length );
  321. }
  322. // Update `operationsA` and `operationsB` with the transformed versions.
  323. operationsA.splice( i, 1, ...newOpsA );
  324. operationsB.splice( indexB, 1, ...newOpsB );
  325. }
  326. if ( options.padWithNoOps ) {
  327. // If no-operations padding is enabled, count how many extra `a` and `b` operations were generated.
  328. const brokenOperationsACount = operationsA.length - data.originalOperationsACount;
  329. const brokenOperationsBCount = operationsB.length - data.originalOperationsBCount;
  330. // Then, if that number is not the same, pad `operationsA` or `operationsB` with correct number of no-ops so
  331. // that the base versions are equalled.
  332. //
  333. // Note that only one array will be updated, as only one of those subtractions can be greater than zero.
  334. padWithNoOps( operationsA, brokenOperationsBCount - brokenOperationsACount );
  335. padWithNoOps( operationsB, brokenOperationsACount - brokenOperationsBCount );
  336. }
  337. // Finally, update base versions of transformed operations.
  338. updateBaseVersions( operationsA, data.nextBaseVersionB );
  339. updateBaseVersions( operationsB, data.nextBaseVersionA );
  340. return { operationsA, operationsB };
  341. }
  342. // Gathers additional data about operations processed during transformation. Can be used to obtain contextual information
  343. // about two operations that are about to be transformed. This contextual information can be used for better conflict resolution.
  344. class ContextFactory {
  345. // Creates `ContextFactory` instance.
  346. //
  347. // @param {module:engine/model/document~Document} document Document which the operations change.
  348. // @param {Boolean} useContext Whether during transformation additional context information should be gathered and used.
  349. constructor( document, useContext ) {
  350. // `model.History` instance which information about undone operations will be taken from.
  351. this._history = document.history;
  352. // Whether additional context should be used.
  353. this._useContext = useContext;
  354. // For each operation that is created during transformation process, we keep a reference to the original operation
  355. // which it comes from. The original operation works as a kind of "identifier". Every contextual information
  356. // gathered during transformation that we want to save for given operation, is actually saved for the original operation.
  357. // This way no matter if operation `a` is cloned, then transformed, even breaks, we still have access to the previously
  358. // gathered data through original operation reference.
  359. this._originalOperations = new Map();
  360. // Relations is a double-map structure (maps in map) where for two operations we store how those operations were related
  361. // to each other. Those relations are evaluated during transformation process. For every transformated pair of operations
  362. // we keep relations between them.
  363. this._relations = new Map();
  364. }
  365. // Sets "original operation" for given operations.
  366. //
  367. // During transformation process, operations are cloned, then changed, then processed again, sometimes broken into two
  368. // or multiple operations. When gathering additional data it is important that all operations can be somehow linked
  369. // so a cloned and transformed "version" still kept track of the data assigned earlier to it.
  370. //
  371. // The original operation object will be used as such an universal linking id. Throughout the transformation process
  372. // all cloned operations will refer to "the original operation" when storing and reading additional data.
  373. //
  374. // If `takeFrom` is not set, each operation from `operations` array will be assigned itself as "the original operation".
  375. // This should be used as an initialization step.
  376. //
  377. // If `takeFrom` is set, each operation from `operations` will be assigned the same original operation as assigned
  378. // for `takeFrom` operation. This should be used to update original operations. It should be used in a way that
  379. // `operations` are the result of `takeFrom` transformation to ensure proper "original operation propagation".
  380. //
  381. // @param {Array.<module:engine/model/operation/operation~Operation>} operations
  382. // @param {module:engine/model/operation/operation~Operation|null} [takeFrom=null]
  383. setOriginalOperations( operations, takeFrom = null ) {
  384. const originalOperation = takeFrom ? this._originalOperations.get( takeFrom ) : null;
  385. for ( const operation of operations ) {
  386. this._originalOperations.set( operation, originalOperation || operation );
  387. }
  388. }
  389. // Saves a relation between operations `opA` and `opB`.
  390. //
  391. // Relations are then later used to help solve conflicts when operations are transformed.
  392. //
  393. // @param {module:engine/model/operation/operation~Operation} opA
  394. // @param {module:engine/model/operation/operation~Operation} opB
  395. updateRelation( opA, opB ) {
  396. // The use of relations is described in a bigger detail in transformation functions.
  397. //
  398. // In brief, this function, for specified pairs of operation types, checks how positions defined in those operations relate.
  399. // Then those relations are saved. For example, for two move operations, it is saved if one of those operations target
  400. // position is before the other operation source position. This kind of information gives contextual information when
  401. // transformation is used during undo. Similar checks are done for other pairs of operations.
  402. //
  403. switch ( opA.constructor ) {
  404. case MoveOperation: {
  405. switch ( opB.constructor ) {
  406. case MergeOperation: {
  407. if ( opA.targetPosition.isEqual( opB.sourcePosition ) || opB.movedRange.containsPosition( opA.targetPosition ) ) {
  408. this._setRelation( opA, opB, 'insertAtSource' );
  409. } else if ( opA.targetPosition.isEqual( opB.deletionPosition ) ) {
  410. this._setRelation( opA, opB, 'insertBetween' );
  411. }
  412. break;
  413. }
  414. case MoveOperation: {
  415. if ( opA.targetPosition.isEqual( opB.sourcePosition ) || opA.targetPosition.isBefore( opB.sourcePosition ) ) {
  416. this._setRelation( opA, opB, 'insertBefore' );
  417. } else {
  418. this._setRelation( opA, opB, 'insertAfter' );
  419. }
  420. break;
  421. }
  422. case UnwrapOperation: {
  423. const isInside = opA.targetPosition.hasSameParentAs( opB.position );
  424. if ( isInside ) {
  425. this._setRelation( opA, opB, 'insertInside' );
  426. }
  427. break;
  428. }
  429. }
  430. break;
  431. }
  432. case SplitOperation: {
  433. switch ( opB.constructor ) {
  434. case MergeOperation: {
  435. if ( opA.position.isBefore( opB.sourcePosition ) ) {
  436. this._setRelation( opA, opB, 'splitBefore' );
  437. }
  438. break;
  439. }
  440. case MoveOperation: {
  441. if ( opA.position.isEqual( opB.sourcePosition ) || opA.position.isBefore( opB.sourcePosition ) ) {
  442. this._setRelation( opA, opB, 'splitBefore' );
  443. }
  444. break;
  445. }
  446. }
  447. break;
  448. }
  449. }
  450. }
  451. // Evaluates and returns contextual information about two given operations `opA` and `opB` which are about to be transformed.
  452. //
  453. // @param {module:engine/model/operation/operation~Operation} opA
  454. // @param {module:engine/model/operation/operation~Operation} opB
  455. // @returns {module:engine/model/operation/transform~TransformationContext}
  456. getContext( opA, opB, aIsStrong ) {
  457. if ( !this._useContext ) {
  458. return {
  459. aIsStrong,
  460. aWasUndone: false,
  461. bWasUndone: false,
  462. abRelation: null,
  463. baRelation: null
  464. };
  465. }
  466. return {
  467. aIsStrong,
  468. aWasUndone: this._wasUndone( opA ),
  469. bWasUndone: this._wasUndone( opB ),
  470. abRelation: this._getRelation( opA, opB ),
  471. baRelation: this._getRelation( opB, opA )
  472. };
  473. }
  474. // Returns whether given operation `op` has already been undone.
  475. //
  476. // This is only used when additional context mode is on (options.useContext == true).
  477. //
  478. // Information whether an operation was undone gives more context when making a decision when two operations are in conflict.
  479. //
  480. // @param {module:engine/model/operation/operation~Operation} op
  481. // @returns {Boolean}
  482. _wasUndone( op ) {
  483. // For `op`, get its original operation. After all, if `op` is a clone (or even transformed clone) of another
  484. // operation, literally `op` couldn't be undone. It was just generated. If anything, it was the operation it origins
  485. // from which was undone. So get that original operation.
  486. const originalOp = this._originalOperations.get( op );
  487. // And check with the document if the original operation was undone.
  488. return this._history.isUndoneOperation( originalOp );
  489. }
  490. // Returns a relation between `opA` and an operation which is undone by `opB`. This can be `String` value if a relation
  491. // was set earlier or `null` if there was no relation between those operations.
  492. //
  493. // This is only used when additional context mode is on (options.useContext == true).
  494. //
  495. // This is a little tricky to understand, so let's compare it to `ContextFactory#_wasUndone`.
  496. //
  497. // When `wasUndone( opB )` is used, we check if the `opB` has already been undone. It is obvious, that the
  498. // undoing operation must happen after the undone operation. So, essentially, we have `opB`, we take document history,
  499. // we look forward in the future and ask if in that future `opB` was undone.
  500. //
  501. // Relations is a backward process to `wasUndone()`.
  502. //
  503. // Long story short - using relations is asking what happened in the past. Looking back. This time we have an undoing
  504. // operation `opB` which has undone some other operation. When there is a transformation `opA` x `opB` and there is
  505. // a conflict to solve and `opB` is an undoing operation, we can look back in the history and see what was a relation
  506. // between `opA` and the operation which `opB` undone. Basing on that relation from the past, we can now make
  507. // a better decision when resolving a conflict between two operations, because we know more about the context of
  508. // those two operations.
  509. //
  510. // This is why this function does not return a relation directly between `opA` and `opB` because we need to look
  511. // back to search for a meaningful contextual information.
  512. //
  513. // @param {module:engine/model/operation/operation~Operation} opA
  514. // @param {module:engine/model/operation/operation~Operation} opB
  515. // @returns {String|null}
  516. _getRelation( opA, opB ) {
  517. // Get the original operation. Similarly as in `wasUndone()` it is used as an universal identifier for stored data.
  518. const origB = this._originalOperations.get( opB );
  519. const undoneB = this._history.getUndoneOperation( origB );
  520. // If `opB` is not undoing any operation, there is no relation.
  521. if ( !undoneB ) {
  522. return null;
  523. }
  524. const origA = this._originalOperations.get( opA );
  525. const relationsA = this._relations.get( origA );
  526. // Get all relations for `opA`, and check if there is a relation with `opB`-undone-counterpart. If so, return it.
  527. if ( relationsA ) {
  528. return relationsA.get( undoneB ) || null;
  529. }
  530. return null;
  531. }
  532. // Helper function for `ContextFactory#updateRelations`.
  533. //
  534. // @private
  535. // @param {module:engine/model/operation/operation~Operation} opA
  536. // @param {module:engine/model/operation/operation~Operation} opB
  537. // @param {String} relation
  538. _setRelation( opA, opB, relation ) {
  539. // As always, setting is for original operations, not the clones/transformed operations.
  540. const origA = this._originalOperations.get( opA );
  541. const origB = this._originalOperations.get( opB );
  542. let relationsA = this._relations.get( origA );
  543. if ( !relationsA ) {
  544. relationsA = new Map();
  545. this._relations.set( origA, relationsA );
  546. }
  547. relationsA.set( origB, relation );
  548. }
  549. }
  550. /**
  551. * Holds additional contextual information about a transformed pair of operations (`a` and `b`). Those information
  552. * can be used for better conflict resolving.
  553. *
  554. * @typedef {Object} module:engine/model/operation/transform~TransformationContext
  555. *
  556. * @property {Boolean} aIsStrong Whether `a` is strong operation in this transformation, or weak.
  557. * @property {Boolean} aWasUndone Whether `a` operation was undone.
  558. * @property {Boolean} bWasUndone Whether `b` operation was undone.
  559. * @property {String|null} abRelation The relation between `a` operation and an operation undone by `b` operation.
  560. * @property {String|null} baRelation The relation between `b` operation and an operation undone by `a` operation.
  561. */
  562. /**
  563. * An utility function that updates {@link module:engine/model/operation/operation~Operation#baseVersion base versions}
  564. * of passed operations.
  565. *
  566. * The function simply sets `baseVersion` as a base version of the first passed operation and then increments it for
  567. * each following operation in `operations`.
  568. *
  569. * @private
  570. * @param {Array.<module:engine/model/operation/operation~Operation>} operations Operations to update.
  571. * @param {Number} baseVersion Base version to set for the first operation in `operations`.
  572. */
  573. function updateBaseVersions( operations, baseVersion ) {
  574. for ( const operation of operations ) {
  575. operation.baseVersion = baseVersion++;
  576. }
  577. }
  578. /**
  579. * Adds `howMany` instances of {@link module:engine/model/operation/nooperation~NoOperation} to `operations` set.
  580. *
  581. * @private
  582. * @param {Array.<module:engine/model/operation/operation~Operation>} operations
  583. * @param {Number} howMany
  584. */
  585. function padWithNoOps( operations, howMany ) {
  586. for ( let i = 0; i < howMany; i++ ) {
  587. operations.push( new NoOperation( 0 ) );
  588. }
  589. }
  590. // -----------------------
  591. setTransformation( AttributeOperation, AttributeOperation, ( a, b, context ) => {
  592. if ( a.key === b.key ) {
  593. // If operations attributes are in conflict, check if their ranges intersect and manage them properly.
  594. // First, we want to apply change to the part of a range that has not been changed by the other operation.
  595. const operations = a.range.getDifference( b.range ).map( range => {
  596. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, 0 );
  597. } );
  598. // Then we take care of the common part of ranges.
  599. const common = a.range.getIntersection( b.range );
  600. if ( common ) {
  601. // If this operation is more important, we also want to apply change to the part of the
  602. // original range that has already been changed by the other operation. Since that range
  603. // got changed we also have to update `oldValue`.
  604. if ( context.aIsStrong ) {
  605. operations.push( new AttributeOperation( common, b.key, b.newValue, a.newValue, 0 ) );
  606. }
  607. }
  608. if ( operations.length == 0 ) {
  609. return [ new NoOperation( 0 ) ];
  610. }
  611. return operations;
  612. } else {
  613. // If operations don't conflict, simply return an array containing just a clone of this operation.
  614. return [ a ];
  615. }
  616. } );
  617. setTransformation( AttributeOperation, InsertOperation, ( a, b ) => {
  618. // Case 1:
  619. //
  620. // The attribute operation range includes the position where nodes were inserted.
  621. // There are two possible scenarios: the inserted nodes were text and they should receive attributes or
  622. // the inserted nodes were elements and they should not receive attributes.
  623. //
  624. if ( a.range.start.hasSameParentAs( b.position ) && a.range.containsPosition( b.position ) ) {
  625. // If new nodes should not receive attributes, two separated ranges will be returned.
  626. // Otherwise, one expanded range will be returned.
  627. const range = a.range._getTransformedByInsertion( b.position, b.howMany, !b.shouldReceiveAttributes );
  628. const result = range.map( r => {
  629. return new AttributeOperation( r, a.key, a.oldValue, a.newValue, a.baseVersion );
  630. } );
  631. if ( b.shouldReceiveAttributes ) {
  632. // `AttributeOperation#range` includes some newly inserted text.
  633. // The operation should also change the attribute of that text. An example:
  634. //
  635. // Bold should be applied on the following range:
  636. // <p>Fo[zb]ar</p>
  637. //
  638. // In meantime, new text is typed:
  639. // <p>Fozxxbar</p>
  640. //
  641. // Bold should be applied also on the new text:
  642. // <p>Fo[zxxb]ar</p>
  643. // <p>Fo<$text bold="true">zxxb</$text>ar</p>
  644. //
  645. // There is a special case to consider here to consider.
  646. //
  647. // Consider setting an attribute with multiple possible values, for example `highlight`. The inserted text might
  648. // have already an attribute value applied and the `oldValue` property of the attribute operation might be wrong:
  649. //
  650. // Attribute `highlight="yellow"` should be applied on the following range:
  651. // <p>Fo[zb]ar<p>
  652. //
  653. // In meantime, character `x` with `highlight="red"` is typed:
  654. // <p>Fo[z<$text highlight="red">x</$text>b]ar</p>
  655. //
  656. // In this case we cannot simply apply operation changing the attribute value from `null` to `"yellow"` for the whole range
  657. // because that would lead to an exception (`oldValue` is incorrect for `x`).
  658. //
  659. // We also cannot break the original range as this would mess up a scenario when there are multiple following
  660. // insert operations, because then only the first inserted character is included in those ranges:
  661. // <p>Fo[z][x][b]ar</p> --> <p>Fo[z][x]x[b]ar</p> --> <p>Fo[z][x]xx[b]ar</p>
  662. //
  663. // So, the attribute range needs be expanded, no matter what attributes are set on the inserted nodes:
  664. //
  665. // <p>Fo[z<$text highlight="red">x</$text>b]ar</p> <--- Change from `null` to `yellow`, throwing an exception.
  666. //
  667. // But before that operation would be applied, we will add an additional attribute operation that will change
  668. // attributes on the inserted nodes in a way which would make the original operation correct:
  669. //
  670. // <p>Fo[z{<$text highlight="red">}x</$text>b]ar</p> <--- Change range `{}` from `red` to `null`.
  671. // <p>Fo[zxb]ar</p> <--- Now change from `null` to `yellow` is completely fine.
  672. //
  673. // Generate complementary attribute operation. Be sure to add it before the original operation.
  674. const op = _getComplementaryAttributeOperations( b, a.key, a.oldValue );
  675. if ( op ) {
  676. result.unshift( op );
  677. }
  678. }
  679. // If nodes should not receive new attribute, we are done here.
  680. return result;
  681. }
  682. // If insert operation is not expanding the attribute operation range, simply transform the range.
  683. a.range = a.range._getTransformedByInsertion( b.position, b.howMany, false )[ 0 ];
  684. return [ a ];
  685. } );
  686. /**
  687. * Helper function for `AttributeOperation` x `InsertOperation` (and reverse) transformation.
  688. *
  689. * For given `insertOperation` it checks the inserted node if it has an attribute `key` set to a value different
  690. * than `newValue`. If so, it generates an `AttributeOperation` which changes the value of `key` attribute to `newValue`.
  691. *
  692. * @private
  693. * @param {module:engine/model/operation/insertoperation~InsertOperation} insertOperation
  694. * @param {String} key
  695. * @param {*} newValue
  696. * @returns {module:engine/model/operation/attributeoperation~AttributeOperation|null}
  697. */
  698. function _getComplementaryAttributeOperations( insertOperation, key, newValue ) {
  699. const nodes = insertOperation.nodes;
  700. // At the beginning we store the attribute value from the first node.
  701. const insertValue = nodes.getNode( 0 ).getAttribute( key );
  702. if ( insertValue == newValue ) {
  703. return null;
  704. }
  705. const range = new Range( insertOperation.position, insertOperation.position.getShiftedBy( insertOperation.howMany ) );
  706. return new AttributeOperation( range, key, insertValue, newValue, 0 );
  707. }
  708. setTransformation( AttributeOperation, MergeOperation, ( a, b ) => {
  709. const ranges = [];
  710. // Case 1:
  711. //
  712. // Attribute change on the merged element. In this case, the merged element was moved to the graveyard.
  713. // An additional attribute operation that will change the (re)moved element needs to be generated.
  714. //
  715. if ( a.range.start.hasSameParentAs( b.deletionPosition ) ) {
  716. if ( a.range.containsPosition( b.deletionPosition ) || a.range.start.isEqual( b.deletionPosition ) ) {
  717. ranges.push( Range.createFromPositionAndShift( b.graveyardPosition, 1 ) );
  718. }
  719. }
  720. const range = a.range._getTransformedByMergeOperation( b );
  721. // Do not add empty (collapsed) ranges to the result. `range` may be collapsed if it contained only the merged element.
  722. if ( !range.isCollapsed ) {
  723. ranges.push( range );
  724. }
  725. // Create `AttributeOperation`s out of the ranges.
  726. return ranges.map( range => {
  727. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion );
  728. } );
  729. } );
  730. setTransformation( AttributeOperation, MoveOperation, ( a, b ) => {
  731. const ranges = _breakRangeByMoveOperation( a.range, b );
  732. // Create `AttributeOperation`s out of the ranges.
  733. return ranges.map( range => new AttributeOperation( range, a.key, a.oldValue, a.newValue, a.baseVersion ) );
  734. } );
  735. // Helper function for `AttributeOperation` x `MoveOperation` transformation.
  736. //
  737. // Takes the passed `range` and transforms it by move operation `moveOp` in a specific way. Only top-level nodes of `range`
  738. // are considered to be in the range. If move operation moves nodes deep from inside of the range, those nodes won't
  739. // be included in the result. In other words, top-level nodes of the ranges from the result are exactly the same as
  740. // top-level nodes of the original `range`.
  741. //
  742. // This is important for `AttributeOperation` because, for its range, it changes only the top-level nodes. So we need to
  743. // track only how those nodes have been affected by `MoveOperation`.
  744. //
  745. // @private
  746. // @param {module:engine/model/range~Range} range
  747. // @param {module:engine/model/operation/moveoperation~MoveOperation} moveOp
  748. // @returns {Array.<module:engine/model/range~Range>}
  749. function _breakRangeByMoveOperation( range, moveOp ) {
  750. const moveRange = Range.createFromPositionAndShift( moveOp.sourcePosition, moveOp.howMany );
  751. // We are transforming `range` (original range) by `moveRange` (range moved by move operation). As usual when it comes to
  752. // transforming a ranges, we may have a common part of the ranges and we may have a difference part (zero to two ranges).
  753. let common = null;
  754. let difference = [];
  755. // Let's compare the ranges.
  756. if ( moveRange.containsRange( range, true ) ) {
  757. // If the whole original range is moved, treat it whole as a common part. There's also no difference part.
  758. common = range;
  759. } else if ( range.start.hasSameParentAs( moveRange.start ) ) {
  760. // If the ranges are "on the same level" (in the same parent) then move operation may move exactly those nodes
  761. // that are changed by the attribute operation. In this case we get common part and difference part in the usual way.
  762. difference = range.getDifference( moveRange );
  763. common = range.getIntersection( moveRange );
  764. } else {
  765. // In any other situation we assume that original range is different than move range, that is that move operation
  766. // moves other nodes that attribute operation change. Even if the moved range is deep inside in the original range.
  767. //
  768. // Note that this is different than in `.getIntersection` (we would get a common part in that case) and different
  769. // than `.getDifference` (we would get two ranges).
  770. difference = [ range ];
  771. }
  772. const result = [];
  773. // The default behaviour of `_getTransformedByMove` might get wrong results for difference part, though, so
  774. // we do it by hand.
  775. for ( let diff of difference ) {
  776. // First, transform the range by removing moved nodes. Since this is a difference, this is safe, `null` won't be returned
  777. // as the range is different than the moved range.
  778. diff = diff._getTransformedByDeletion( moveOp.sourcePosition, moveOp.howMany );
  779. // Transform also `targetPosition`.
  780. const targetPosition = moveOp.getMovedRangeStart();
  781. // Spread the range only if moved nodes are inserted only between the top-level nodes of the `diff` range.
  782. const spread = diff.start.hasSameParentAs( targetPosition );
  783. // Transform by insertion of moved nodes.
  784. diff = diff._getTransformedByInsertion( targetPosition, moveOp.howMany, spread );
  785. result.push( ...diff );
  786. }
  787. // Common part can be simply transformed by the move operation. This is because move operation will not target to
  788. // that common part (the operation would have to target inside its own moved range).
  789. if ( common ) {
  790. result.push(
  791. common._getTransformedByMove( moveOp.sourcePosition, moveOp.targetPosition, moveOp.howMany, false )[ 0 ]
  792. );
  793. }
  794. return result;
  795. }
  796. setTransformation( AttributeOperation, SplitOperation, ( a, b ) => {
  797. // Case 1:
  798. //
  799. // Split node is the last node in `AttributeOperation#range`.
  800. // `AttributeOperation#range` needs to be expanded to include the new (split) node.
  801. //
  802. // Attribute `type` to be changed to `numbered` but the `listItem` is split.
  803. // <listItem type="bulleted">foobar</listItem>
  804. //
  805. // After split:
  806. // <listItem type="bulleted">foo</listItem><listItem type="bulleted">bar</listItem>
  807. //
  808. // After attribute change:
  809. // <listItem type="numbered">foo</listItem><listItem type="numbered">foo</listItem>
  810. //
  811. if ( a.range.end.isEqual( b.insertionPosition ) && !b.graveyardPosition ) {
  812. a.range.end.offset++;
  813. return [ a ];
  814. }
  815. // Case 2:
  816. //
  817. // Split position is inside `AttributeOperation#range`, at the same level, so the nodes to change are
  818. // not going to make a flat range.
  819. //
  820. // Content with range-to-change and split position:
  821. // <p>Fo[zb^a]r</p>
  822. //
  823. // After split:
  824. // <p>Fozb</p><p>ar</p>
  825. //
  826. // Make two separate ranges containing all nodes to change:
  827. // <p>Fo[zb]</p><p>[a]r</p>
  828. //
  829. if ( a.range.start.hasSameParentAs( b.position ) && a.range.containsPosition( b.position ) ) {
  830. const secondPart = a.clone();
  831. secondPart.range = new Range(
  832. Position.createFromPosition( b.moveTargetPosition ),
  833. a.range.end._getCombined( b.position, b.moveTargetPosition )
  834. );
  835. a.range.end = Position.createFromPosition( b.position );
  836. a.range.end.stickiness = 'toPrevious';
  837. return [ a, secondPart ];
  838. }
  839. // The default case.
  840. //
  841. a.range = a.range._getTransformedBySplitOperation( b );
  842. return [ a ];
  843. } );
  844. setTransformation( AttributeOperation, WrapOperation, ( a, b ) => {
  845. // Case 1:
  846. //
  847. // `AttributeOperation#range` and range to wrap intersect. Multiple `AttributeOperation`s may be needed
  848. // to handle this situation as, after wrapping, the nodes to change may be in different parents.
  849. //
  850. // Both list items' type should be changed to numbered:
  851. // [<listItem type="bulleted">Foo</listItem><listItem type="bulleted">Bar</listItem>]
  852. //
  853. // Wrap one of the items inside block quote:
  854. // <blockQuote><listItem type="bulleted">Foo</listItem></blockQuote><listItem type="bulleted">Bar</listItem>
  855. //
  856. // Two operations are needed:
  857. // <blockQuote>[<listItem type="bulleted">Foo</listItem>]</blockQuote>[<listItem type="bulleted">Bar</listItem>]
  858. //
  859. // Up to there operations/ranges might be needed in other cases.
  860. //
  861. if ( a.range.start.hasSameParentAs( b.position ) ) {
  862. const ranges = a.range.getDifference( b.wrappedRange );
  863. const common = a.range.getIntersection( b.wrappedRange );
  864. if ( common ) {
  865. ranges.push( common );
  866. }
  867. // Create `AttributeOperation`s out of the ranges.
  868. return ranges.map( range => {
  869. return new AttributeOperation( range._getTransformedByWrapOperation( b ), a.key, a.oldValue, a.newValue, 0 );
  870. } );
  871. }
  872. // The default case.
  873. //
  874. a.range = a.range._getTransformedByWrapOperation( b );
  875. return [ a ];
  876. } );
  877. setTransformation( AttributeOperation, UnwrapOperation, ( a, b ) => {
  878. // Case 1:
  879. //
  880. // `AttributeOperation#range` contains element to unwrap. Two or three `AttributeOperation`s are needed to handle this
  881. // situation. The unwrapped element was moved to graveyard and needs a separate operation. Then, if the unwrapped
  882. // nodes end up inside the attribute operation range, the range needs to be broken on two parts.
  883. //
  884. if ( a.range.start.hasSameParentAs( b.targetPosition ) ) {
  885. const insertionPosition = b.targetPosition.getShiftedBy( b.howMany );
  886. let ranges = a.range._getTransformedByInsertion( b.targetPosition, b.howMany );
  887. ranges = ranges.reduce( ( result, range ) => {
  888. return result.concat( range._getTransformedByMove( insertionPosition, b.graveyardPosition, 1 ) );
  889. }, [] );
  890. // Create `AttributeOperation`s out of the ranges.
  891. return ranges.map( range => {
  892. return new AttributeOperation( range, a.key, a.oldValue, a.newValue, 0 );
  893. } );
  894. }
  895. // The default case.
  896. //
  897. a.range = a.range._getTransformedByUnwrapOperation( b );
  898. return [ a ];
  899. } );
  900. // -----------------------
  901. setTransformation( InsertOperation, AttributeOperation, ( a, b ) => {
  902. const result = [ a ];
  903. // Case 1:
  904. //
  905. // The attribute operation range includes the position where nodes were inserted.
  906. // There are two possible scenarios: the inserted nodes were text and they should receive attributes or
  907. // the inserted nodes were elements and they should not receive attributes.
  908. //
  909. // This is a mirror scenario to the one described in `AttributeOperation` x `InsertOperation` transformation,
  910. // although this case is a little less complicated. In this case we simply need to change attributes of the
  911. // inserted nodes and that's it.
  912. //
  913. if ( a.shouldReceiveAttributes && a.position.hasSameParentAs( b.range.start ) && b.range.containsPosition( a.position ) ) {
  914. const op = _getComplementaryAttributeOperations( a, b.key, b.newValue );
  915. if ( op ) {
  916. result.push( op );
  917. }
  918. }
  919. // The default case is: do nothing.
  920. // `AttributeOperation` does not change the model tree structure so `InsertOperation` does not need to be changed.
  921. //
  922. return result;
  923. } );
  924. setTransformation( InsertOperation, InsertOperation, ( a, b, context ) => {
  925. // Case 1:
  926. //
  927. // Two insert operations insert nodes at the same position. Since they are the same, it needs to be decided
  928. // what will be the order of inserted nodes. However, there is no additional information to help in that
  929. // decision. Also, when `b` will be transformed by `a`, the same order must be maintained.
  930. //
  931. // To achieve that, we will check if the operation is strong.
  932. // If it is, it won't get transformed. If it is not, it will be moved.
  933. //
  934. if ( a.position.isEqual( b.position ) && context.aIsStrong ) {
  935. return [ a ];
  936. }
  937. // The default case.
  938. //
  939. a.position = a.position._getTransformedByInsertOperation( b );
  940. return [ a ];
  941. } );
  942. setTransformation( InsertOperation, MoveOperation, ( a, b ) => {
  943. // The default case.
  944. //
  945. a.position = a.position._getTransformedByMoveOperation( b );
  946. return [ a ];
  947. } );
  948. setTransformation( InsertOperation, SplitOperation, ( a, b ) => {
  949. // The default case.
  950. //
  951. a.position = a.position._getTransformedBySplitOperation( b );
  952. return [ a ];
  953. } );
  954. setTransformation( InsertOperation, MergeOperation, ( a, b ) => {
  955. a.position = a.position._getTransformedByMergeOperation( b );
  956. return [ a ];
  957. } );
  958. setTransformation( InsertOperation, WrapOperation, ( a, b ) => {
  959. // The default case.
  960. //
  961. a.position = a.position._getTransformedByWrapOperation( b );
  962. return [ a ];
  963. } );
  964. setTransformation( InsertOperation, UnwrapOperation, ( a, b ) => {
  965. a.position = a.position._getTransformedByUnwrapOperation( b );
  966. return [ a ];
  967. } );
  968. // -----------------------
  969. setTransformation( MarkerOperation, InsertOperation, ( a, b ) => {
  970. if ( a.oldRange ) {
  971. a.oldRange = a.oldRange._getTransformedByInsertOperation( b )[ 0 ];
  972. }
  973. if ( a.newRange ) {
  974. a.newRange = a.newRange._getTransformedByInsertOperation( b )[ 0 ];
  975. }
  976. return [ a ];
  977. } );
  978. setTransformation( MarkerOperation, MarkerOperation, ( a, b, context ) => {
  979. if ( a.name == b.name ) {
  980. if ( context.aIsStrong ) {
  981. a.oldRange = b.newRange ? Range.createFromRange( b.newRange ) : null;
  982. } else {
  983. return [ new NoOperation( 0 ) ];
  984. }
  985. }
  986. return [ a ];
  987. } );
  988. setTransformation( MarkerOperation, MergeOperation, ( a, b ) => {
  989. if ( a.oldRange ) {
  990. a.oldRange = a.oldRange._getTransformedByMergeOperation( b );
  991. }
  992. if ( a.newRange ) {
  993. a.newRange = a.newRange._getTransformedByMergeOperation( b );
  994. }
  995. return [ a ];
  996. } );
  997. setTransformation( MarkerOperation, MoveOperation, ( a, b ) => {
  998. if ( a.oldRange ) {
  999. a.oldRange = Range.createFromRanges( a.oldRange._getTransformedByMoveOperation( b ) );
  1000. }
  1001. if ( a.newRange ) {
  1002. a.newRange = Range.createFromRanges( a.newRange._getTransformedByMoveOperation( b ) );
  1003. }
  1004. return [ a ];
  1005. } );
  1006. setTransformation( MarkerOperation, SplitOperation, ( a, b ) => {
  1007. if ( a.oldRange ) {
  1008. a.oldRange = a.oldRange._getTransformedBySplitOperation( b );
  1009. }
  1010. if ( a.newRange ) {
  1011. a.newRange = a.newRange._getTransformedBySplitOperation( b );
  1012. }
  1013. return [ a ];
  1014. } );
  1015. setTransformation( MarkerOperation, WrapOperation, ( a, b ) => {
  1016. if ( a.oldRange ) {
  1017. a.oldRange = a.oldRange._getTransformedByWrapOperation( b );
  1018. }
  1019. if ( a.newRange ) {
  1020. a.newRange = a.newRange._getTransformedByWrapOperation( b );
  1021. }
  1022. return [ a ];
  1023. } );
  1024. setTransformation( MarkerOperation, UnwrapOperation, ( a, b ) => {
  1025. if ( a.oldRange ) {
  1026. a.oldRange = a.oldRange._getTransformedByUnwrapOperation( b );
  1027. }
  1028. if ( a.newRange ) {
  1029. a.newRange = a.newRange._getTransformedByUnwrapOperation( b );
  1030. }
  1031. return [ a ];
  1032. } );
  1033. // -----------------------
  1034. setTransformation( MergeOperation, InsertOperation, ( a, b ) => {
  1035. if ( a.sourcePosition.hasSameParentAs( b.position ) ) {
  1036. a.howMany += b.howMany;
  1037. }
  1038. a.sourcePosition = a.sourcePosition._getTransformedByInsertOperation( b );
  1039. a.targetPosition = a.targetPosition._getTransformedByInsertOperation( b );
  1040. return [ a ];
  1041. } );
  1042. setTransformation( MergeOperation, MergeOperation, ( a, b, context ) => {
  1043. // Case 1:
  1044. //
  1045. // Same merge operations.
  1046. //
  1047. // Both operations have same source and target positions. So the element already got merged and there is
  1048. // theoretically nothing to do.
  1049. //
  1050. // In this case, keep the source operation in the merged element - in the graveyard - and don't change target position.
  1051. // Doing this instead of returning `NoOperation` allows for a correct undo later.
  1052. //
  1053. if ( a.sourcePosition.isEqual( b.sourcePosition ) && a.targetPosition.isEqual( b.targetPosition ) ) {
  1054. const path = b.graveyardPosition.path.slice();
  1055. path.push( 0 );
  1056. a.sourcePosition = new Position( b.graveyardPosition.root, path );
  1057. a.howMany = 0;
  1058. return [ a ];
  1059. }
  1060. // The default case.
  1061. //
  1062. if ( a.sourcePosition.hasSameParentAs( b.targetPosition ) ) {
  1063. a.howMany += b.howMany;
  1064. }
  1065. a.sourcePosition = a.sourcePosition._getTransformedByMergeOperation( b );
  1066. a.targetPosition = a.targetPosition._getTransformedByMergeOperation( b );
  1067. // Handle positions in graveyard.
  1068. // If graveyard positions are same and `a` operation is strong - do not transform.
  1069. if ( !a.graveyardPosition.isEqual( b.graveyardPosition ) || !context.aIsStrong ) {
  1070. a.graveyardPosition._getTransformedByInsertion( b.graveyardPosition, 1 );
  1071. }
  1072. return [ a ];
  1073. } );
  1074. setTransformation( MergeOperation, MoveOperation, ( a, b, context ) => {
  1075. // Case 1:
  1076. //
  1077. // The element to merge got removed.
  1078. //
  1079. // Merge operation does support merging elements which are not siblings. So it would not be a problem
  1080. // from technical point of view. However, if the element was removed, the intention of the user deleting it
  1081. // was to have it all deleted, together with its children. From user experience point of view, moving back the
  1082. // removed nodes might be unexpected. This means that in this scenario we will block the merging.
  1083. //
  1084. // The exception of this rule would be if the remove operation was later undone.
  1085. //
  1086. const removedRange = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  1087. if ( b.type == 'remove' && !context.bWasUndone ) {
  1088. if ( a.deletionPosition.hasSameParentAs( b.sourcePosition ) && removedRange.containsPosition( a.sourcePosition ) ) {
  1089. return [ new NoOperation( 0 ) ];
  1090. }
  1091. }
  1092. // The default case.
  1093. //
  1094. if ( a.sourcePosition.hasSameParentAs( b.targetPosition ) ) {
  1095. a.howMany += b.howMany;
  1096. }
  1097. if ( a.sourcePosition.hasSameParentAs( b.sourcePosition ) ) {
  1098. a.howMany -= b.howMany;
  1099. }
  1100. a.sourcePosition = a.sourcePosition._getTransformedByMoveOperation( b );
  1101. a.targetPosition = a.targetPosition._getTransformedByMoveOperation( b );
  1102. // `MergeOperation` graveyard position is like `MoveOperation` target position. It is a position where element(s) will
  1103. // be moved. Like in other similar cases, we need to consider the scenario when those positions are same.
  1104. // Here, we will treat `MergeOperation` like it is always strong (see `InsertOperation` x `InsertOperation` for comparison).
  1105. // This means that we won't transform graveyard position if it is equal to move operation target position.
  1106. if ( !a.graveyardPosition.isEqual( b.targetPosition ) ) {
  1107. a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation( b );
  1108. }
  1109. return [ a ];
  1110. } );
  1111. setTransformation( MergeOperation, SplitOperation, ( a, b ) => {
  1112. if ( b.graveyardPosition ) {
  1113. // If `b` operation defines graveyard position, a node from graveyard will be moved. This means that we need to
  1114. // transform `a.graveyardPosition` accordingly.
  1115. a.graveyardPosition = a.graveyardPosition._getTransformedByDeletion( b.graveyardPosition, 1 );
  1116. // This is a scenario foreseen in `MergeOperation` x `MergeOperation`, with two identical merge operations.
  1117. //
  1118. // So, there was `MergeOperation` x `MergeOperation` transformation earlier. Now, `a` is a merge operation which
  1119. // source position is in graveyard. Interestingly, split operation wants to use the node to be merged by `a`. This
  1120. // means that `b` is undoing that merge operation from earlier, which caused `a` to be in graveyard.
  1121. //
  1122. // If that's the case, at this point, we will only "fix" `a.howMany`. It was earlier set to `0` in
  1123. // `MergeOperation` x `MergeOperation` transformation. Later transformations in this function will change other
  1124. // properties.
  1125. //
  1126. if ( a.deletionPosition.isEqual( b.graveyardPosition ) ) {
  1127. a.howMany = b.howMany;
  1128. }
  1129. }
  1130. // Case 1:
  1131. //
  1132. // Merge operation moves nodes to the place where split happens.
  1133. // This is a classic situation when there are two paragraphs, and there is a split (enter) after the first
  1134. // paragraph and there is a merge (delete) at the beginning of the second paragraph:
  1135. //
  1136. // <p>Foo{}</p><p>[]Bar</p>.
  1137. //
  1138. // Split is after `Foo`, while merge is from `Bar` to the end of `Foo`.
  1139. //
  1140. // State after split:
  1141. // <p>Foo</p><p></p><p>Bar</p>
  1142. //
  1143. // Now, `Bar` should be merged to the new paragraph:
  1144. // <p>Foo</p><p>Bar</p>
  1145. //
  1146. // Instead of merging it to the original paragraph:
  1147. // <p>FooBar</p><p></p>
  1148. //
  1149. // This means that `targetPosition` needs to be transformed. This is the default case though.
  1150. // For example, if the split would be after `F`, `targetPosition` should also be transformed.
  1151. //
  1152. // There are two exception, though, when we want to keep `targetPosition` as it was.
  1153. //
  1154. // First exception is when the merge target position is inside an element (not at the end, as usual). This
  1155. // happens when the merge operation earlier was transformed by "the same" merge operation. If merge operation
  1156. // targets inside the element we want to keep the original target position (and not transform it) because
  1157. // we have additional context telling us that we want to merge to the original element. We can check if the
  1158. // merge operation points inside element by checking what is `SplitOperation#howMany`. Since merge target position
  1159. // is same as split position, if `howMany` is non-zero, it means that the merge target position is inside an element.
  1160. //
  1161. // Second exception is when the element to merge is in the graveyard and split operation uses it. In that case
  1162. // if target position would be transformed, the merge operation would target at the source position:
  1163. //
  1164. // root: <p>Foo</p> graveyard: <p></p>
  1165. //
  1166. // SplitOperation: root [ 0, 3 ] using graveyard [ 0 ] (howMany = 0)
  1167. // MergeOperation: graveyard [ 0, 0 ] -> root [ 0, 3 ] (howMany = 0)
  1168. //
  1169. // Since split operation moves the graveyard node back to the root, the merge operation source position changes.
  1170. // We would like to merge from the empty <p> to the "Foo" <p>:
  1171. //
  1172. // root: <p>Foo</p><p></p> graveyard:
  1173. //
  1174. // MergeOperation#sourcePosition = root [ 1, 0 ]
  1175. //
  1176. // If `targetPosition` is transformed, it would become root [ 1, 0 ] as well. It has to be kept as it was.
  1177. //
  1178. if ( a.targetPosition.isEqual( b.position ) ) {
  1179. if ( b.howMany != 0 || ( b.graveyardPosition && a.deletionPosition.isEqual( b.graveyardPosition ) ) ) {
  1180. a.sourcePosition = a.sourcePosition._getTransformedBySplitOperation( b );
  1181. return [ a ];
  1182. }
  1183. }
  1184. // The default case.
  1185. //
  1186. if ( a.sourcePosition.hasSameParentAs( b.position ) ) {
  1187. a.howMany = b.position.offset;
  1188. }
  1189. a.sourcePosition = a.sourcePosition._getTransformedBySplitOperation( b );
  1190. a.targetPosition = a.targetPosition._getTransformedBySplitOperation( b );
  1191. return [ a ];
  1192. } );
  1193. setTransformation( MergeOperation, WrapOperation, ( a, b ) => {
  1194. if ( b.graveyardPosition ) {
  1195. a.graveyardPosition = a.graveyardPosition._getTransformedByDeletion( b.graveyardPosition, 1 );
  1196. }
  1197. if ( a.sourcePosition.hasSameParentAs( b.position ) ) {
  1198. a.howMany = a.howMany + 1 - b.howMany;
  1199. }
  1200. // Case 2:
  1201. //
  1202. // Merged element is wrapped and this is the last (only) element in the wrap.
  1203. // Because of how this is resolved in `WrapOperation` x `MergeOperation`, we need to apply special handling here.
  1204. // If the last element from wrapped range is "removed" from it, the wrap is effectively on empty range.
  1205. // In that case, the wrapper element is moved to graveyard. This happens in `WrapOperation` x
  1206. // `MergeOperation` and we need to mirror it here.
  1207. //
  1208. if ( b.position.isEqual( a.deletionPosition ) && b.howMany == 1 ) {
  1209. // We need to change `MergeOperation#graveyardPosition` so the merged node is moved into the wrapper element.
  1210. // Since `UnwrapOperation` created from reverse has graveyard position at [ 0 ], we can safely set the path here to [ 0, 0 ].
  1211. a.graveyardPosition = new Position( a.graveyardPosition.root, [ 0, 0 ] );
  1212. return [
  1213. b.getReversed(),
  1214. a
  1215. ];
  1216. }
  1217. // The default case.
  1218. //
  1219. a.sourcePosition = a.sourcePosition._getTransformedByWrapOperation( b );
  1220. a.targetPosition = a.targetPosition._getTransformedByWrapOperation( b );
  1221. return [ a ];
  1222. } );
  1223. setTransformation( MergeOperation, UnwrapOperation, ( a, b, context ) => {
  1224. // Case 1:
  1225. //
  1226. // The element to merge got unwrapped.
  1227. //
  1228. // There are multiple possible solutions to resolve this conflict:
  1229. //
  1230. // * unwrap also merge target (all nodes are unwrapped),
  1231. // * move the unwrapped nodes to the merge target (no nodes stayed unwrapped),
  1232. // * leave merge position in the unwrapped node (some nodes are unwrapped and some are not).
  1233. //
  1234. // Third option is chosen in this algorithm. If the unwrap operation is undone before merge is applied,
  1235. // the merge operation will work as expected. If the unwrap operation is not undone, then the merge
  1236. // operation won't merge any nodes, so it will behave similarly to noop.
  1237. //
  1238. if ( a.sourcePosition.isEqual( b.position ) ) {
  1239. const path = b.graveyardPosition.path.slice();
  1240. path.push( 0 );
  1241. a.sourcePosition = new Position( b.graveyardPosition.root, path );
  1242. a.howMany = 0;
  1243. return [ a ];
  1244. }
  1245. // Case 2: The element to merge into got unwrapped.
  1246. //
  1247. // In this case there is nothing to merge into. We can imagine, that the merge operation was a little earlier
  1248. // than unwrap operation, so first elements got merged, and then both were unwrapped. To simulate this,
  1249. // we will change this merge into unwrap.
  1250. //
  1251. // We have this:
  1252. // <blockQuote><p>Foo</p></blockQuote><blockQuote><p>Bar</p></blockQuote>
  1253. //
  1254. // Unwrap already happened:
  1255. // <p>Foo</p><blockQuote><p>Bar</p></blockQuote>
  1256. //
  1257. // Let's act like merge happened first and lead to this state:
  1258. // <p>Foo</p><p>Bar</p>
  1259. //
  1260. if ( a.targetPosition.hasSameParentAs( b.position ) ) {
  1261. const graveyard = a.sourcePosition.root.document.graveyard;
  1262. const graveyardPosition = new Position( graveyard, [ 0 ] );
  1263. return [ new UnwrapOperation( a.sourcePosition, a.howMany, graveyardPosition, 0 ) ];
  1264. }
  1265. // The default case.
  1266. //
  1267. if ( a.sourcePosition.hasSameParentAs( b.targetPosition ) ) {
  1268. a.howMany = a.howMany - 1 + b.howMany;
  1269. }
  1270. a.sourcePosition = a.sourcePosition._getTransformedByUnwrapOperation( b );
  1271. a.targetPosition = a.targetPosition._getTransformedByUnwrapOperation( b );
  1272. // Handle positions in graveyard.
  1273. // If graveyard positions are same and `a` operation is strong - do not transform.
  1274. if ( !a.graveyardPosition.isEqual( b.graveyardPosition ) || !context.aIsStrong ) {
  1275. a.graveyardPosition._getTransformedByInsertion( b.graveyardPosition, 1 );
  1276. }
  1277. return [ a ];
  1278. } );
  1279. // -----------------------
  1280. setTransformation( MoveOperation, InsertOperation, ( a, b ) => {
  1281. const moveRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1282. const transformed = moveRange._getTransformedByInsertOperation( b, false )[ 0 ];
  1283. a.sourcePosition = transformed.start;
  1284. a.howMany = transformed.end.offset - transformed.start.offset;
  1285. // See `InsertOperation` x `MoveOperation` transformation for details on this case.
  1286. //
  1287. // In summary, both operations point to the same place, so the order of nodes needs to be decided.
  1288. // `MoveOperation` is considered weaker, so it is always transformed, unless there was a certain relation
  1289. // between operations.
  1290. //
  1291. if ( !a.targetPosition.isEqual( b.position ) ) {
  1292. a.targetPosition = a.targetPosition._getTransformedByInsertOperation( b );
  1293. }
  1294. return [ a ];
  1295. } );
  1296. setTransformation( MoveOperation, MoveOperation, ( a, b, context ) => {
  1297. //
  1298. // Setting and evaluating some variables that will be used in special cases and default algorithm.
  1299. //
  1300. // Create ranges from `MoveOperations` properties.
  1301. const rangeA = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1302. const rangeB = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  1303. // Assign `context.aIsStrong` to a different variable, because the value may change during execution of
  1304. // this algorithm and we do not want to override original `context.aIsStrong` that will be used in later transformations.
  1305. let aIsStrong = context.aIsStrong;
  1306. // This will be used to decide the order of nodes if both operations target at the same position.
  1307. // By default, use strong/weak operation mechanism.
  1308. let insertBefore = !context.aIsStrong;
  1309. // If the relation is set, then use it to decide nodes order.
  1310. if ( context.abRelation == 'insertBefore' ) {
  1311. insertBefore = true;
  1312. } else if ( context.abRelation == 'insertAfter' ) {
  1313. insertBefore = false;
  1314. }
  1315. // `a.targetPosition` could be affected by the `b` operation. We will transform it.
  1316. let newTargetPosition;
  1317. if ( a.targetPosition.isEqual( b.targetPosition ) && insertBefore ) {
  1318. newTargetPosition = a.targetPosition._getTransformedByDeletion(
  1319. b.sourcePosition,
  1320. b.howMany
  1321. );
  1322. } else {
  1323. newTargetPosition = a.targetPosition._getTransformedByMove(
  1324. b.sourcePosition,
  1325. b.targetPosition,
  1326. b.howMany
  1327. );
  1328. }
  1329. //
  1330. // Special case #1 + mirror.
  1331. //
  1332. // Special case when both move operations' target positions are inside nodes that are
  1333. // being moved by the other move operation. So in other words, we move ranges into inside of each other.
  1334. // This case can't be solved reasonably (on the other hand, it should not happen often).
  1335. if ( _moveTargetIntoMovedRange( a, b ) && _moveTargetIntoMovedRange( b, a ) ) {
  1336. // Instead of transforming operation, we return a reverse of the operation that we transform by.
  1337. // So when the results of this "transformation" will be applied, `b` MoveOperation will get reversed.
  1338. return [ b.getReversed() ];
  1339. }
  1340. //
  1341. // End of special case #1.
  1342. //
  1343. //
  1344. // Special case #2.
  1345. //
  1346. // Check if `b` operation targets inside `rangeA`. Use stickiness if possible.
  1347. const bTargetsToA = rangeA.containsPosition( b.targetPosition );
  1348. // If `b` targets to `rangeA` and `rangeA` contains `rangeB`, `b` operation has no influence on `a` operation.
  1349. // You might say that operation `b` is captured inside operation `a`.
  1350. if ( bTargetsToA && rangeA.containsRange( rangeB, true ) ) {
  1351. // There is a mini-special case here, where `rangeB` is on other level than `rangeA`. That's why
  1352. // we need to transform `a` operation anyway.
  1353. rangeA.start = rangeA.start._getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany );
  1354. rangeA.end = rangeA.end._getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany );
  1355. return _makeMoveOperationsFromRanges( [ rangeA ], newTargetPosition );
  1356. }
  1357. //
  1358. // Special case #2 mirror.
  1359. //
  1360. const aTargetsToB = rangeB.containsPosition( a.targetPosition );
  1361. if ( aTargetsToB && rangeB.containsRange( rangeA, true ) ) {
  1362. // `a` operation is "moved together" with `b` operation.
  1363. // Here, just move `rangeA` "inside" `rangeB`.
  1364. rangeA.start = rangeA.start._getCombined( b.sourcePosition, b.getMovedRangeStart() );
  1365. rangeA.end = rangeA.end._getCombined( b.sourcePosition, b.getMovedRangeStart() );
  1366. return _makeMoveOperationsFromRanges( [ rangeA ], newTargetPosition );
  1367. }
  1368. //
  1369. // End of special case #2.
  1370. //
  1371. //
  1372. // Special case #3 + mirror.
  1373. //
  1374. // `rangeA` has a node which is an ancestor of `rangeB`. In other words, `rangeB` is inside `rangeA`
  1375. // but not on the same tree level. In such case ranges have common part but we have to treat it
  1376. // differently, because in such case those ranges are not really conflicting and should be treated like
  1377. // two separate ranges. Also we have to discard two difference parts.
  1378. const aCompB = compareArrays( a.sourcePosition.getParentPath(), b.sourcePosition.getParentPath() );
  1379. if ( aCompB == 'prefix' || aCompB == 'extension' ) {
  1380. // Transform `rangeA` by `b` operation and make operation out of it, and that's all.
  1381. // Note that this is a simplified version of default case, but here we treat the common part (whole `rangeA`)
  1382. // like a one difference part.
  1383. rangeA.start = rangeA.start._getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany );
  1384. rangeA.end = rangeA.end._getTransformedByMove( b.sourcePosition, b.targetPosition, b.howMany );
  1385. return _makeMoveOperationsFromRanges( [ rangeA ], newTargetPosition );
  1386. }
  1387. //
  1388. // End of special case #3.
  1389. //
  1390. //
  1391. // Default case - ranges are on the same level or are not connected with each other.
  1392. //
  1393. // Modifier for default case.
  1394. // Modifies `aIsStrong` flag in certain conditions.
  1395. //
  1396. // If only one of operations is a remove operation, we force remove operation to be the "stronger" one
  1397. // to provide more expected results.
  1398. if ( a.type == 'remove' && b.type != 'remove' && !context.aWasUndone ) {
  1399. aIsStrong = true;
  1400. } else if ( a.type != 'remove' && b.type == 'remove' && !context.bWasUndone ) {
  1401. aIsStrong = false;
  1402. }
  1403. // Handle operation's source ranges - check how `rangeA` is affected by `b` operation.
  1404. // This will aggregate transformed ranges.
  1405. const ranges = [];
  1406. // Get the "difference part" of `a` operation source range.
  1407. // This is an array with one or two ranges. Two ranges if `rangeB` is inside `rangeA`.
  1408. const difference = rangeA.getDifference( rangeB );
  1409. for ( const range of difference ) {
  1410. // Transform those ranges by `b` operation. For example if `b` moved range from before those ranges, fix those ranges.
  1411. range.start = range.start._getTransformedByDeletion( b.sourcePosition, b.howMany );
  1412. range.end = range.end._getTransformedByDeletion( b.sourcePosition, b.howMany );
  1413. // If `b` operation targets into `rangeA` on the same level, spread `rangeA` into two ranges.
  1414. const shouldSpread = compareArrays( range.start.getParentPath(), b.getMovedRangeStart().getParentPath() ) == 'same';
  1415. const newRanges = range._getTransformedByInsertion( b.getMovedRangeStart(), b.howMany, shouldSpread );
  1416. ranges.push( ...newRanges );
  1417. }
  1418. // Then, we have to manage the "common part" of both move ranges.
  1419. const common = rangeA.getIntersection( rangeB );
  1420. if ( common !== null && aIsStrong && !bTargetsToA ) {
  1421. // Calculate the new position of that part of original range.
  1422. common.start = common.start._getCombined( b.sourcePosition, b.getMovedRangeStart() );
  1423. common.end = common.end._getCombined( b.sourcePosition, b.getMovedRangeStart() );
  1424. // Take care of proper range order.
  1425. //
  1426. // Put `common` at appropriate place. Keep in mind that we are interested in original order.
  1427. // Basically there are only three cases: there is zero, one or two difference ranges.
  1428. //
  1429. // If there is zero difference ranges, just push `common` in the array.
  1430. if ( ranges.length === 0 ) {
  1431. ranges.push( common );
  1432. }
  1433. // If there is one difference range, we need to check whether common part was before it or after it.
  1434. else if ( ranges.length == 1 ) {
  1435. if ( rangeB.start.isBefore( rangeA.start ) || rangeB.start.isEqual( rangeA.start ) ) {
  1436. ranges.unshift( common );
  1437. } else {
  1438. ranges.push( common );
  1439. }
  1440. }
  1441. // If there are more ranges (which means two), put common part between them. This is the only scenario
  1442. // where there could be two difference ranges so we don't have to make any comparisons.
  1443. else {
  1444. ranges.splice( 1, 0, common );
  1445. }
  1446. }
  1447. if ( ranges.length === 0 ) {
  1448. // If there are no "source ranges", nothing should be changed.
  1449. // Note that this can happen only if `aIsStrong == false` and `rangeA.isEqual( rangeB )`.
  1450. return [ new NoOperation( a.baseVersion ) ];
  1451. }
  1452. return _makeMoveOperationsFromRanges( ranges, newTargetPosition );
  1453. } );
  1454. setTransformation( MoveOperation, SplitOperation, ( a, b, context ) => {
  1455. let newTargetPosition = a.targetPosition._getTransformedBySplitOperation( b );
  1456. // Case 1:
  1457. //
  1458. // Last element in the moved range got split.
  1459. //
  1460. // In this case the default range transformation will not work correctly as the element created by
  1461. // split operation would be outside the range. The range to move needs to be fixed manually.
  1462. // Do it only if this is a "natural" split, not a one that comes from undo.
  1463. // TODO: this should be done on relations
  1464. //
  1465. const moveRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1466. if ( moveRange.end.isEqual( b.insertionPosition ) && !b.graveyardPosition ) {
  1467. a.howMany++;
  1468. a.targetPosition = newTargetPosition;
  1469. return [ a ];
  1470. }
  1471. // Case 2:
  1472. //
  1473. // Split happened between the moved nodes. In this case two ranges to move need to be generated.
  1474. //
  1475. // Characters `ozba` are moved to the end of paragraph `Xyz` but split happened.
  1476. // <p>F[oz|ba]r</p><p>Xyz</p>
  1477. //
  1478. // After split:
  1479. // <p>F[oz</p><p>ba]r</p><p>Xyz</p>
  1480. //
  1481. // Correct ranges:
  1482. // <p>F[oz]</p><p>[ba]r</p><p>Xyz</p>
  1483. //
  1484. // After move:
  1485. // <p>F</p><p>r</p><p>Xyzozba</p>
  1486. //
  1487. if ( moveRange.start.hasSameParentAs( b.position ) && moveRange.containsPosition( b.position ) ) {
  1488. let rightRange = new Range( b.position, moveRange.end );
  1489. rightRange = rightRange._getTransformedBySplitOperation( b );
  1490. const ranges = [
  1491. new Range( moveRange.start, b.position ),
  1492. rightRange
  1493. ];
  1494. return _makeMoveOperationsFromRanges( ranges, newTargetPosition );
  1495. }
  1496. // Case 3:
  1497. //
  1498. // Move operation targets at the split position. We need to decide if the nodes should be inserted
  1499. // at the end of the split element or at the beginning of the new element.
  1500. //
  1501. if ( a.targetPosition.isEqual( b.position ) && context.abRelation == 'insertAtSource' ) {
  1502. newTargetPosition = b.moveTargetPosition;
  1503. }
  1504. // Case 4:
  1505. //
  1506. // Move operation targets just after the split element. We need to decide if the nodes should be inserted
  1507. // between two parts of split element, or after the new element.
  1508. //
  1509. // Split at `|`, while move operation moves `<p>Xyz</p>` and targets at `^`:
  1510. // <p>Foo|bar</p>^<p>baz</p>
  1511. // <p>Foo</p>^<p>bar</p><p>baz</p> or <p>Foo</p><p>bar</p>^<p>baz</p>?
  1512. //
  1513. // If there is no contextual information between operations (for example, they come from collaborative
  1514. // editing), we don't want to put some unrelated content (move) between parts of related content (split parts).
  1515. // However, if the split is from undo, in the past, the moved content might be targeting between the
  1516. // split parts, meaning that was exactly user's intention:
  1517. //
  1518. // <p>Foo</p>^<p>bar</p> <--- original situation, in "past".
  1519. // <p>Foobar</p>^ <--- after merge target position is transformed.
  1520. // <p>Foo|bar</p>^ <--- then the merge is undone, and split happens, which leads us to current situation.
  1521. //
  1522. // In this case it is pretty clear that the intention was to put new paragraph between those nodes,
  1523. // so we need to transform accordingly. We can detect this scenario thanks to relations.
  1524. //
  1525. if ( a.targetPosition.isEqual( b.insertionPosition ) && context.abRelation == 'insertBetween' ) {
  1526. newTargetPosition = a.targetPosition;
  1527. }
  1528. // The default case.
  1529. //
  1530. const transformed = moveRange._getTransformedBySplitOperation( b );
  1531. a.sourcePosition = transformed.start;
  1532. a.howMany = transformed.end.offset - transformed.start.offset;
  1533. a.targetPosition = newTargetPosition;
  1534. return [ a ];
  1535. } );
  1536. setTransformation( MoveOperation, MergeOperation, ( a, b, context ) => {
  1537. const movedRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1538. if ( b.deletionPosition.hasSameParentAs( a.sourcePosition ) && movedRange.containsPosition( b.sourcePosition ) ) {
  1539. if ( a.type == 'remove' ) {
  1540. // Case 1:
  1541. //
  1542. // The element to remove got merged.
  1543. //
  1544. // Merge operation does support merging elements which are not siblings. So it would not be a problem
  1545. // from technical point of view. However, if the element was removed, the intention of the user
  1546. // deleting it was to have it all deleted. From user experience point of view, moving back the
  1547. // removed nodes might be unexpected. This means that in this scenario we will reverse merging and remove the element.
  1548. //
  1549. if ( !context.aWasUndone ) {
  1550. return [ b.getReversed(), a ];
  1551. }
  1552. } else {
  1553. // Case 2:
  1554. //
  1555. // The element to move got merged and it was the only element to move.
  1556. // In this case just don't do anything, leave the node in the graveyard. Without special case
  1557. // it would be a move operation that moves 0 nodes, so maybe it is better just to return no-op.
  1558. //
  1559. if ( a.howMany == 1 ) {
  1560. if ( !context.bWasUndone ) {
  1561. return [ new NoOperation( 0 ) ];
  1562. } else {
  1563. a.sourcePosition = Position.createFromPosition( b.graveyardPosition );
  1564. a.targetPosition = a.targetPosition._getTransformedByMergeOperation( b );
  1565. return [ a ];
  1566. }
  1567. }
  1568. }
  1569. }
  1570. // The default case.
  1571. //
  1572. const moveRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1573. const transformed = moveRange._getTransformedByMergeOperation( b );
  1574. a.sourcePosition = transformed.start;
  1575. a.howMany = transformed.end.offset - transformed.start.offset;
  1576. a.targetPosition = a.targetPosition._getTransformedByMergeOperation( b );
  1577. return [ a ];
  1578. } );
  1579. setTransformation( MoveOperation, WrapOperation, ( a, b, context ) => {
  1580. const moveRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1581. let newTargetPosition = a.targetPosition._getTransformedByWrapOperation( b );
  1582. // Case 1:
  1583. //
  1584. // Move operation targets to the beginning of the wrapped range. We need to decide if the moved nodes
  1585. // should also be wrapped.
  1586. //
  1587. if ( a.targetPosition.isEqual( b.position ) && context.abRelation == 'insertInside' ) {
  1588. newTargetPosition = b.targetPosition;
  1589. }
  1590. // Case 2:
  1591. //
  1592. // Some of the nodes to move got wrapped. In this case multiple ranges to move might need to be generated.
  1593. //
  1594. // First paragraph and the image should are wrapped, while the two images are moved after the last paragraph:
  1595. // [<paragraph>Foo</paragraph>{<image />]<image />}<paragraph>Bar</paragraph>
  1596. //
  1597. // After wrap:
  1598. // <blockQuote><paragraph>Foo</paragraph>[<image />]</blockQuote>[<image />]<paragraph>Bar</paragraph>
  1599. //
  1600. // After move:
  1601. // <blockQuote><paragraph>Foo</paragraph></blockQuote><paragraph>Bar</paragraph><image /><image />
  1602. //
  1603. if ( a.sourcePosition.hasSameParentAs( b.position ) ) {
  1604. // If move range contains or is equal to the wrapped range, just move it all together.
  1605. // Change `howMany` to reflect that nodes got wrapped.
  1606. if ( moveRange.containsRange( b.wrappedRange, true ) ) {
  1607. a.howMany = a.howMany - b.howMany + 1;
  1608. return [ a ];
  1609. }
  1610. const result = [];
  1611. let difference = moveRange.getDifference( b.wrappedRange )[ 0 ];
  1612. let common = moveRange.getIntersection( b.wrappedRange );
  1613. if ( difference ) {
  1614. difference = difference._getTransformedByWrapOperation( b );
  1615. result.push( new MoveOperation( difference.start, difference.end.offset - difference.start.offset, newTargetPosition, 0 ) );
  1616. }
  1617. if ( common ) {
  1618. common = common._getTransformedByWrapOperation( b );
  1619. result.push( new MoveOperation( common.start, common.end.offset - common.start.offset, newTargetPosition, 0 ) );
  1620. }
  1621. return result;
  1622. }
  1623. // The default case.
  1624. //
  1625. const transformed = moveRange._getTransformedByWrapOperation( b );
  1626. a.sourcePosition = transformed.start;
  1627. a.howMany = transformed.end.offset - transformed.start.offset;
  1628. a.targetPosition = newTargetPosition;
  1629. return [ a ];
  1630. } );
  1631. setTransformation( MoveOperation, UnwrapOperation, ( a, b ) => {
  1632. const moveRange = Range.createFromPositionAndShift( a.sourcePosition, a.howMany );
  1633. const transformed = moveRange._getTransformedByUnwrapOperation( b );
  1634. a.sourcePosition = transformed.start;
  1635. a.howMany = transformed.end.offset - transformed.start.offset;
  1636. a.targetPosition = a.targetPosition._getTransformedByUnwrapOperation( b );
  1637. return [ a ];
  1638. } );
  1639. // -----------------------
  1640. setTransformation( RenameOperation, InsertOperation, ( a, b ) => {
  1641. a.position = a.position._getTransformedByInsertOperation( b );
  1642. return [ a ];
  1643. } );
  1644. setTransformation( RenameOperation, MergeOperation, ( a, b ) => {
  1645. // Case 1:
  1646. //
  1647. // Element to rename got merged, so it was moved to `b.graveyardPosition`.
  1648. //
  1649. if ( a.position.isEqual( b.deletionPosition ) ) {
  1650. a.position = Position.createFromPosition( b.graveyardPosition );
  1651. a.position.stickiness = 'toNext';
  1652. return [ a ];
  1653. }
  1654. a.position = a.position._getTransformedByMergeOperation( b );
  1655. return [ a ];
  1656. } );
  1657. setTransformation( RenameOperation, MoveOperation, ( a, b ) => {
  1658. a.position = a.position._getTransformedByMoveOperation( b );
  1659. return [ a ];
  1660. } );
  1661. setTransformation( RenameOperation, RenameOperation, ( a, b, context ) => {
  1662. if ( a.position.isEqual( b.position ) ) {
  1663. if ( context.aIsStrong ) {
  1664. a.oldName = b.newName;
  1665. } else {
  1666. return [ new NoOperation( 0 ) ];
  1667. }
  1668. }
  1669. return [ a ];
  1670. } );
  1671. setTransformation( RenameOperation, SplitOperation, ( a, b ) => {
  1672. // Case 1:
  1673. //
  1674. // The element to rename has been split. In this case, the new element should be also renamed.
  1675. //
  1676. // User decides to change the paragraph to a list item:
  1677. // <paragraph>Foobar</paragraph>
  1678. //
  1679. // However, in meantime, split happens:
  1680. // <paragraph>Foo</paragraph><paragraph>bar</paragraph>
  1681. //
  1682. // As a result, rename both elements:
  1683. // <listItem>Foo</listItem><listItem>bar</listItem>
  1684. //
  1685. const renamePath = a.position.path;
  1686. const splitPath = b.position.getParentPath();
  1687. if ( compareArrays( renamePath, splitPath ) == 'same' && !b.graveyardPosition ) {
  1688. const extraRename = new RenameOperation( a.position.getShiftedBy( 1 ), a.oldName, a.newName, 0 );
  1689. return [ a, extraRename ];
  1690. }
  1691. // The default case.
  1692. //
  1693. a.position = a.position._getTransformedBySplitOperation( b );
  1694. return [ a ];
  1695. } );
  1696. setTransformation( RenameOperation, WrapOperation, ( a, b ) => {
  1697. a.position = a.position._getTransformedByWrapOperation( b );
  1698. return [ a ];
  1699. } );
  1700. setTransformation( RenameOperation, UnwrapOperation, ( a, b ) => {
  1701. // Case 1:
  1702. //
  1703. // Element to rename got unwrapped, so it was moved to `b.graveyardPosition`.
  1704. //
  1705. if ( a.position.isEqual( b.targetPosition ) ) {
  1706. a.position = Position.createFromPosition( b.graveyardPosition );
  1707. return [ a ];
  1708. }
  1709. a.position = a.position._getTransformedByUnwrapOperation( b );
  1710. return [ a ];
  1711. } );
  1712. // -----------------------
  1713. setTransformation( RootAttributeOperation, RootAttributeOperation, ( a, b, context ) => {
  1714. if ( a.root === b.root && a.key === b.key ) {
  1715. if ( !context.aIsStrong || a.newValue === b.newValue ) {
  1716. return [ new NoOperation( 0 ) ];
  1717. } else {
  1718. a.oldValue = b.newValue;
  1719. }
  1720. }
  1721. return [ a ];
  1722. } );
  1723. // -----------------------
  1724. setTransformation( SplitOperation, InsertOperation, ( a, b ) => {
  1725. // The default case.
  1726. //
  1727. if ( a.position.hasSameParentAs( b.position ) && a.position.offset < b.position.offset ) {
  1728. a.howMany += b.howMany;
  1729. }
  1730. a.position = a.position._getTransformedByInsertOperation( b );
  1731. return [ a ];
  1732. } );
  1733. setTransformation( SplitOperation, MergeOperation, ( a, b ) => {
  1734. if ( a.position.hasSameParentAs( b.deletionPosition ) && !a.position.isAfter( b.deletionPosition ) ) {
  1735. a.howMany--;
  1736. }
  1737. if ( a.position.hasSameParentAs( b.targetPosition ) ) {
  1738. a.howMany += b.howMany;
  1739. }
  1740. a.position = a.position._getTransformedByMergeOperation( b );
  1741. if ( a.graveyardPosition ) {
  1742. a.graveyardPosition = a.graveyardPosition._getTransformedByMergeOperation( b );
  1743. }
  1744. return [ a ];
  1745. } );
  1746. setTransformation( SplitOperation, MoveOperation, ( a, b, context ) => {
  1747. if ( a.graveyardPosition ) {
  1748. a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation( b );
  1749. }
  1750. // Case 1:
  1751. //
  1752. // If the split position is inside the moved range, we need to shift the split position to a proper place.
  1753. // The position cannot be moved together with moved range because that would result in splitting of an incorrect element.
  1754. //
  1755. // Characters `bc` should be moved to the second paragraph while split position is between them:
  1756. // <paragraph>A[b|c]d</paragraph><paragraph>Xyz</paragraph>
  1757. //
  1758. // After move, new split position is incorrect:
  1759. // <paragraph>Ad</paragraph><paragraph>Xb|cyz</paragraph>
  1760. //
  1761. // Correct split position:
  1762. // <paragraph>A|d</paragraph><paragraph>Xbcyz</paragraph>
  1763. //
  1764. // After split:
  1765. // <paragraph>A</paragraph><paragraph>d</paragraph><paragraph>Xbcyz</paragraph>
  1766. //
  1767. const rangeToMove = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  1768. if ( a.position.hasSameParentAs( b.sourcePosition ) && rangeToMove.containsPosition( a.position ) ) {
  1769. const howManyRemoved = b.howMany - ( a.position.offset - b.sourcePosition.offset );
  1770. a.howMany -= howManyRemoved;
  1771. if ( a.position.hasSameParentAs( b.targetPosition ) && a.position.offset < b.targetPosition.offset ) {
  1772. a.howMany += b.howMany;
  1773. }
  1774. a.position = Position.createFromPosition( b.sourcePosition );
  1775. return [ a ];
  1776. }
  1777. // Case 2:
  1778. //
  1779. // Split is at a position where nodes were moved.
  1780. //
  1781. // This is a scenario described in `MoveOperation` x `SplitOperation` transformation but from the
  1782. // "split operation point of view".
  1783. //
  1784. if ( a.position.isEqual( b.targetPosition ) && ( context.baRelation == 'insertAtSource' || context.abRelation == 'splitBefore' ) ) {
  1785. a.howMany += b.howMany;
  1786. a.position = a.position._getTransformedByDeletion( b.sourcePosition, b.howMany );
  1787. return [ a ];
  1788. }
  1789. // The default case.
  1790. //
  1791. if ( a.position.hasSameParentAs( b.sourcePosition ) && a.position.offset <= b.sourcePosition.offset ) {
  1792. a.howMany -= b.howMany;
  1793. }
  1794. if ( a.position.hasSameParentAs( b.targetPosition ) && a.position.offset < b.targetPosition.offset ) {
  1795. a.howMany += b.howMany;
  1796. }
  1797. // Change position stickiness to force a correct transformation.
  1798. a.position.stickiness = 'toNone';
  1799. a.position = a.position._getTransformedByMoveOperation( b );
  1800. a.position.stickiness = 'toNext';
  1801. return [ a ];
  1802. } );
  1803. setTransformation( SplitOperation, SplitOperation, ( a, b, context ) => {
  1804. // Case 1:
  1805. //
  1806. // Split at the same position.
  1807. //
  1808. // If there already was a split at the same position as in `a` operation, it means that the intention
  1809. // conveyed by `a` operation has already been fulfilled and `a` should not do anything (to avoid double split).
  1810. //
  1811. // However, there is a difference if these are new splits or splits created by undo. These have different
  1812. // intentions. Also splits moving back different elements from graveyard have different intentions. They
  1813. // are just different operations.
  1814. //
  1815. // So we cancel split operation only if it was really identical.
  1816. //
  1817. if ( a.position.isEqual( b.position ) ) {
  1818. if ( !a.graveyardPosition && !b.graveyardPosition ) {
  1819. return [ new NoOperation( 0 ) ];
  1820. }
  1821. if ( a.graveyardPosition && b.graveyardPosition && a.graveyardPosition.isEqual( b.graveyardPosition ) ) {
  1822. return [ new NoOperation( 0 ) ];
  1823. }
  1824. }
  1825. if ( a.graveyardPosition && b.graveyardPosition ) {
  1826. a.graveyardPosition = a.graveyardPosition._getTransformedByDeletion( b.graveyardPosition, 1 );
  1827. }
  1828. // Case 2:
  1829. //
  1830. // Position where operation `b` inserted a new node after split is the same as the operation `a` split position.
  1831. // As in similar cases, there is ambiguity if the split should be before the new node (created by `b`) or after.
  1832. //
  1833. if ( a.position.isEqual( b.insertionPosition ) && context.abRelation == 'splitBefore' ) {
  1834. a.howMany++;
  1835. return [ a ];
  1836. }
  1837. // Case 3:
  1838. //
  1839. // This is a mirror to the case 2. above.
  1840. //
  1841. if ( b.position.isEqual( a.insertionPosition ) && context.baRelation == 'splitBefore' ) {
  1842. const newPositionPath = b.insertionPosition.path.slice();
  1843. newPositionPath.push( 0 );
  1844. const newPosition = new Position( b.insertionPosition.root, newPositionPath );
  1845. const moveOp = new MoveOperation( a.insertionPosition, 1, newPosition, 0 );
  1846. return [ a, moveOp ];
  1847. }
  1848. // The default case.
  1849. //
  1850. if ( a.position.hasSameParentAs( b.position ) && a.position.offset < b.position.offset ) {
  1851. a.howMany -= b.howMany;
  1852. }
  1853. a.position = a.position._getTransformedBySplitOperation( b );
  1854. return [ a ];
  1855. } );
  1856. setTransformation( SplitOperation, WrapOperation, ( a, b ) => {
  1857. if ( a.graveyardPosition ) {
  1858. a.graveyardPosition = a.graveyardPosition._getTransformedByWrapOperation( b );
  1859. }
  1860. // Case 1:
  1861. //
  1862. // If split position has been wrapped, reverse the wrapping so that split can be applied as intended.
  1863. // This is an edge case scenario where it is difficult to find a correct solution.
  1864. // Since it will be a rare (or only theoretical) scenario, the algorithm will perform the easy solution.
  1865. //
  1866. if ( a.position.hasSameParentAs( b.position ) && b.wrappedRange.containsPosition( a.position ) ) {
  1867. const reversed = b.getReversed();
  1868. return [ reversed, a ];
  1869. }
  1870. // Case 2:
  1871. //
  1872. // Split position is in a wrapper element in graveyard. This is a case that happens in undo. Earlier, `SplitOperation`
  1873. // was transformed by `UnwrapOperation` and it was left in the unwrapped node. Now the unwrapped node will be re-used
  1874. // and we need to fix `howMany` property in the `SplitOperation`.
  1875. //
  1876. if ( b.graveyardPosition && a.insertionPosition.isEqual( b.graveyardPosition.getShiftedBy( 1 ) ) ) {
  1877. a.position = a.position._getCombined( b.graveyardPosition, b.position );
  1878. a.howMany = a.howMany + b.howMany;
  1879. return [ a ];
  1880. }
  1881. // The default case.
  1882. //
  1883. if ( a.position.hasSameParentAs( b.position ) && a.position.offset < b.position.offset ) {
  1884. a.howMany = a.howMany + 1 - b.howMany;
  1885. }
  1886. a.position = a.position._getTransformedByWrapOperation( b );
  1887. return [ a ];
  1888. } );
  1889. setTransformation( SplitOperation, UnwrapOperation, ( a, b, context ) => {
  1890. if ( a.graveyardPosition ) {
  1891. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( b );
  1892. }
  1893. // Case 1:
  1894. //
  1895. // The element to split got unwrapped.
  1896. //
  1897. // At this moment, there is nothing to split. We probably shouldn't split the "new parent" because that
  1898. // might be very different from the user's intention. Instead, we will leave split position inside the
  1899. // unwrapped element, which is now in graveyard.
  1900. //
  1901. // There is an exception to that - if the unwrap operation got undone. In this case we will follow normal
  1902. // transformation (move split position together with unwrapped nodes). Because later it will be in the wrapper
  1903. // element back again.
  1904. //
  1905. const splitInside = a.position.hasSameParentAs( b.position );
  1906. if ( splitInside ) {
  1907. const path = b.graveyardPosition.path.slice();
  1908. path.push( 0 );
  1909. a.position = new Position( b.graveyardPosition.root, path );
  1910. if ( !context.bWasUndone ) {
  1911. a.howMany = 0;
  1912. } else {
  1913. // New `howMany` will be 0 or below. Will be fixed in SplitOperation x WrapOperation.
  1914. a.howMany = a.howMany - b.howMany;
  1915. }
  1916. return [ a ];
  1917. }
  1918. // The default case.
  1919. //
  1920. if ( a.position.hasSameParentAs( b.targetPosition ) && a.position.offset < b.targetPosition.offset ) {
  1921. a.howMany = a.howMany - 1 + b.howMany;
  1922. }
  1923. a.position = a.position._getTransformedByUnwrapOperation( b );
  1924. return [ a ];
  1925. } );
  1926. // -----------------------
  1927. setTransformation( WrapOperation, InsertOperation, ( a, b ) => {
  1928. // The default case.
  1929. //
  1930. const transformed = a.wrappedRange._getTransformedByInsertOperation( b, false )[ 0 ];
  1931. a.position = transformed.start;
  1932. a.howMany = transformed.end.offset - transformed.start.offset;
  1933. return [ a ];
  1934. } );
  1935. setTransformation( WrapOperation, MergeOperation, ( a, b ) => {
  1936. if ( a.graveyardPosition ) {
  1937. a.graveyardPosition = a.graveyardPosition._getTransformedByInsertion( b.graveyardPosition, 1 );
  1938. }
  1939. // Case 1:
  1940. //
  1941. // The element to wrap got merged and it was the only element to wrap. Let's wrap it in the graveyard.
  1942. //
  1943. if ( a.position.isEqual( b.deletionPosition ) && a.howMany == 1 ) {
  1944. a.position = Position.createFromPosition( b.graveyardPosition );
  1945. a.position.stickiness = 'toNext';
  1946. return [ a ];
  1947. }
  1948. // The default case.
  1949. //
  1950. const transformed = a.wrappedRange._getTransformedByMergeOperation( b );
  1951. a.position = transformed.start;
  1952. a.howMany = transformed.end.offset - transformed.start.offset;
  1953. return [ a ];
  1954. } );
  1955. setTransformation( WrapOperation, MoveOperation, ( a, b, context ) => {
  1956. if ( a.graveyardPosition ) {
  1957. a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation( b );
  1958. }
  1959. // Case 1:
  1960. //
  1961. // Move operation targets to the beginning of the wrapped range.
  1962. // We need to decide if the moved node should also be wrapped.
  1963. //
  1964. if ( a.position.isEqual( b.targetPosition ) && context.baRelation == 'insertInside' ) {
  1965. a.position._getTransformedByDeletion( b.sourcePosition, b.howMany );
  1966. a.howMany += b.howMany;
  1967. return [ a ];
  1968. }
  1969. const moveRange = Range.createFromPositionAndShift( b.sourcePosition, b.howMany );
  1970. const wrappedRange = a.wrappedRange;
  1971. // Case 2:
  1972. //
  1973. // Range to wrap is equal to moved range or is wholly inside the moved range. In other words, all nodes
  1974. // to wrap has been moved. In this case, wrap all of those nodes in their new place.
  1975. //
  1976. // Note that this is different than the default case. In the default case, if only some nodes are moved
  1977. // those moved nodes are not wrapped at their new location. Only those nodes which didn't move are wrapped
  1978. // at their old location.
  1979. //
  1980. if ( moveRange.containsRange( wrappedRange, true ) ) {
  1981. a.position = a.position._getCombined( b.sourcePosition, b.getMovedRangeStart() );
  1982. return [ a ];
  1983. }
  1984. // The default case.
  1985. //
  1986. let transformed = wrappedRange._getTransformedByDeletion( b.sourcePosition, b.howMany );
  1987. transformed = transformed._getTransformedByInsertion( b.targetPosition, b.howMany, false )[ 0 ];
  1988. a.position = transformed.start;
  1989. a.howMany = transformed.end.offset - transformed.start.offset;
  1990. return [ a ];
  1991. } );
  1992. setTransformation( WrapOperation, SplitOperation, ( a, b ) => {
  1993. // Case 1:
  1994. //
  1995. // If range to wrap got split cancel the wrapping. See `SplitOperation` x `WrapOperation`.
  1996. //
  1997. const isInside = a.position.hasSameParentAs( b.position ) && a.wrappedRange.containsPosition( b.position );
  1998. if ( isInside ) {
  1999. // We cannot just return no-op in this case, because in the mirror case scenario the wrap is reversed, which
  2000. // might introduce a new node in the graveyard (if the wrap didn't have `graveyardPosition`, then the wrap
  2001. // created a new element which was put to the graveyard when the wrap was reversed).
  2002. //
  2003. // Instead, a node in graveyard will be inserted.
  2004. //
  2005. if ( a.element ) {
  2006. const graveyard = a.position.root.document.graveyard;
  2007. const graveyardPosition = new Position( graveyard, [ 0 ] );
  2008. return [ new InsertOperation( graveyardPosition, a.element, 0 ) ];
  2009. } else {
  2010. // If `WrapOperation` comes from undo then the, in `SplitOperation` x `WrapOperation`, after it is reversed
  2011. // that element will be moved to graveyard, at offset `0`. We should reflect it here to avoid different
  2012. // graveyard root states.
  2013. //
  2014. const gyPos = new Position( a.graveyardPosition.root, [ 0 ] );
  2015. return [ new MoveOperation( a.graveyardPosition, 1, gyPos, 0 ) ];
  2016. }
  2017. }
  2018. if ( a.graveyardPosition && b.graveyardPosition ) {
  2019. a.graveyardPosition = a.graveyardPosition._getTransformedByDeletion( b.graveyardPosition, 1 );
  2020. }
  2021. // Case 2:
  2022. //
  2023. // If last element from range to wrap has been split, include the newly created element in the wrap range.
  2024. //
  2025. if ( b.insertionPosition.isEqual( a.wrappedRange.end ) ) {
  2026. a.howMany++;
  2027. return [ a ];
  2028. }
  2029. // The default case.
  2030. //
  2031. const transformed = a.wrappedRange._getTransformedBySplitOperation( b );
  2032. a.position = transformed.start;
  2033. a.howMany = transformed.end.offset - transformed.start.offset;
  2034. return [ a ];
  2035. } );
  2036. setTransformation( WrapOperation, WrapOperation, ( a, b, context ) => {
  2037. let newGraveyardPosition = a.graveyardPosition;
  2038. if ( a.graveyardPosition && b.graveyardPosition ) {
  2039. newGraveyardPosition = a.graveyardPosition._getTransformedByDeletion( b.graveyardPosition, 1 );
  2040. }
  2041. // Case 1:
  2042. //
  2043. // If ranges to wrap intersect on the same level then there is a conflict.
  2044. // Depending on `context.aIsStrong` the nodes in the intersecting part should be left as they were wrapped
  2045. // or moved to the new wrapping element.
  2046. //
  2047. // `Foo` and `Bar` are to be wrapped in `blockQuote`, while `Bar` and `Xyz` in `div`.
  2048. // [<paragraph>Foo</paragraph>{<paragraph>Bar</paragraph>]<paragraph>Xyz</paragraph>}
  2049. //
  2050. // After `blockQuote` wrap:
  2051. // <blockQuote>
  2052. // <paragraph>Foo</paragraph><paragraph>Bar</paragraph>
  2053. // </blockQuote>
  2054. // <paragraph>Xyz</paragraph>
  2055. //
  2056. // After `div` wrap:
  2057. // <blockQuote>
  2058. // <paragraph>Foo</paragraph><paragraph>Bar</paragraph>
  2059. // </blockQuote>
  2060. // <div>
  2061. // <paragraph>Xyz</paragraph>
  2062. // </div>
  2063. //
  2064. // Or, if `div` wrap is stronger:
  2065. // <blockQuote>
  2066. // <paragraph>Foo</paragraph>
  2067. // </blockQuote>
  2068. // <div>
  2069. // <paragraph>Bar</paragraph><paragraph>Xyz</paragraph>
  2070. // </div>
  2071. //
  2072. // The range from incoming operation may be also wholly included in the range from operation `b`.
  2073. // Then, cancel the wrapping. The same happens when the ranges are identical but in that case,
  2074. // `context.aIsStrong` decides which wrapping should be cancelled.
  2075. //
  2076. // Lastly, the range from operation `b` may be wholly included in the range from incoming operation.
  2077. // Then, unwrap the range from operation `b` and do a wrap on full range from operation `a`.
  2078. //
  2079. if ( a.position.hasSameParentAs( b.position ) ) {
  2080. const ranges = a.wrappedRange.getDifference( b.wrappedRange );
  2081. // Range from `a` is contained in range from `b` or ranges are equal.
  2082. if ( ranges.length == 0 ) {
  2083. if ( a.wrappedRange.isEqual( b.wrappedRange ) && context.aIsStrong ) {
  2084. // If ranges are equal and `a` is a stronger operation, reverse `b` operation and then apply `a` operation.
  2085. const reversed = b.getReversed();
  2086. if ( a.graveyardPosition ) {
  2087. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( reversed );
  2088. }
  2089. return [ reversed, a ];
  2090. }
  2091. // If `a` is contained in `b` or they are same but `b` is stronger, operation `a` should do nothing.
  2092. // However, to keep the model state same on both clients, it is needed to create a wrapping element in the graveyard.
  2093. const graveyard = a.position.root.document.graveyard;
  2094. a.position = new Position( graveyard, [ 0 ] );
  2095. a.howMany = 0;
  2096. a.graveyardPosition = newGraveyardPosition;
  2097. return [ a ];
  2098. }
  2099. // Ranges intersect.
  2100. else {
  2101. // Range from `b` has some extra nodes other than nodes from `a`.
  2102. if ( !a.wrappedRange.containsRange( b.wrappedRange, true ) ) {
  2103. if ( context.aIsStrong ) {
  2104. // If the incoming wrap operation is strong, we need to reverse the previous wrap, then apply the incoming
  2105. // operation as is, then re-wrap the other nodes that were wrapped in the previous wrap.
  2106. //
  2107. // Content already wrapped into `blockQuote` but that wrap is not strong:
  2108. // <blockQuote><p>Foo</p><p>Bar</p></blockQuote><p>Xyz</p>
  2109. //
  2110. // Unwrap:
  2111. // <p>Foo</p><p>Bar</p><p>Xyz</p>
  2112. //
  2113. // Wrap with stronger wrap:
  2114. // <p>Foo</p><div><p>Bar</p><p>Xyz</p></div>
  2115. //
  2116. // Re-wrap:
  2117. // <blockQuote><p>Foo</p></blockQuote><div><p>Bar</p><p>Xyz</p></div>
  2118. //
  2119. const reversed = b.getReversed();
  2120. if ( a.graveyardPosition ) {
  2121. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( reversed );
  2122. }
  2123. const bOnlyRange = b.wrappedRange.getDifference( a.wrappedRange )[ 0 ];
  2124. const rewrapRange = bOnlyRange._getTransformedByWrapOperation( a );
  2125. const rewrapHowMany = rewrapRange.end.offset - rewrapRange.start.offset;
  2126. const rewrap = new WrapOperation( rewrapRange.start, rewrapHowMany, reversed.graveyardPosition, 0 );
  2127. return [ reversed, a, rewrap ];
  2128. } else {
  2129. // If the incoming wrap operation is not strong, just wrap those nodes which were not wrapped already.
  2130. const range = ranges[ 0 ]._getTransformedByWrapOperation( b );
  2131. a.position = range.start;
  2132. a.howMany = range.end.offset - range.start.offset;
  2133. a.graveyardPosition = newGraveyardPosition;
  2134. return [ a ];
  2135. }
  2136. }
  2137. // Range from `b` is contained in range from `a`. Reverse operation `b` in addition to operation `a`.
  2138. else {
  2139. const reversed = b.getReversed();
  2140. if ( a.graveyardPosition ) {
  2141. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( reversed );
  2142. }
  2143. return [ reversed, a ];
  2144. }
  2145. }
  2146. }
  2147. // The default case.
  2148. //
  2149. const transformed = a.wrappedRange._getTransformedByWrapOperation( b );
  2150. a.position = transformed.start;
  2151. a.howMany = transformed.end.offset - transformed.start.offset;
  2152. a.graveyardPosition = newGraveyardPosition;
  2153. return [ a ];
  2154. } );
  2155. setTransformation( WrapOperation, UnwrapOperation, ( a, b ) => {
  2156. const transformed = a.wrappedRange._getTransformedByUnwrapOperation( b );
  2157. a.position = transformed.start;
  2158. a.howMany = transformed.end.offset - transformed.start.offset;
  2159. if ( a.graveyardPosition ) {
  2160. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( b );
  2161. }
  2162. return [ a ];
  2163. } );
  2164. // -----------------------
  2165. setTransformation( UnwrapOperation, InsertOperation, ( a, b ) => {
  2166. // Case 1:
  2167. //
  2168. // Insert operation inserts nodes into the unwrapped element.
  2169. // This does not have any impact on `UnwrapOperation#position`, but `#howMany` has to be changed.
  2170. //
  2171. if ( a.position.hasSameParentAs( b.position ) ) {
  2172. a.howMany += b.howMany;
  2173. }
  2174. a.position = a.position._getTransformedByInsertOperation( b );
  2175. return [ a ];
  2176. } );
  2177. setTransformation( UnwrapOperation, MergeOperation, ( a, b, context ) => {
  2178. // Case 1:
  2179. //
  2180. // The element to unwrap got merged.
  2181. //
  2182. // There are multiple possible solution to resolve this conflict:
  2183. //
  2184. // * unwrap the merge target element (all nodes are unwrapped),
  2185. // * cancel the unwrap (no nodes stayed unwrapped),
  2186. // * reverse the merge and apply the original unwrap (some nodes are unwrapped and some are not).
  2187. //
  2188. if ( a.position.isEqual( b.sourcePosition ) ) {
  2189. return [ b.getReversed(), a ];
  2190. }
  2191. // The default case.
  2192. //
  2193. // There are some scenarios here where `UnwrapOperation#howMany` needs to be changed, but they are pretty straightforward.
  2194. //
  2195. if ( a.position.hasSameParentAs( b.targetPosition ) ) {
  2196. a.howMany += b.howMany;
  2197. }
  2198. if ( a.position.hasSameParentAs( b.graveyardPosition ) ) {
  2199. a.howMany++;
  2200. }
  2201. if ( a.position.hasSameParentAs( b.deletionPosition ) ) {
  2202. a.howMany--;
  2203. }
  2204. a.position = a.position._getTransformedByMergeOperation( b );
  2205. if ( !a.graveyardPosition.isEqual( b.graveyardPosition ) || !context.aIsStrong ) {
  2206. a.graveyardPosition = a.graveyardPosition._getTransformedByMergeOperation( b );
  2207. }
  2208. return [ a ];
  2209. } );
  2210. setTransformation( UnwrapOperation, MoveOperation, ( a, b ) => {
  2211. // Case 1:
  2212. //
  2213. // Move operation moves nodes from the unwrapped element.
  2214. // This does not have any impact on `UnwrapOperation#position`, but `#howMany` has to be changed.
  2215. //
  2216. if ( a.position.hasSameParentAs( b.sourcePosition ) ) {
  2217. a.howMany -= b.howMany;
  2218. }
  2219. // Case 2:
  2220. //
  2221. // Move operation moves nodes into the unwrapped element.
  2222. // This does not have any impact on `UnwrapOperation#position`, but `#howMany` has to be changed.
  2223. // Note, that case 1 and case 2 may happen together.
  2224. //
  2225. if ( a.position.hasSameParentAs( b.targetPosition ) ) {
  2226. a.howMany += b.howMany;
  2227. }
  2228. // The default case.
  2229. //
  2230. a.position = a.position._getTransformedByMoveOperation( b );
  2231. if ( !a.graveyardPosition.isEqual( b.targetPosition ) ) {
  2232. a.graveyardPosition = a.graveyardPosition._getTransformedByMoveOperation( b );
  2233. }
  2234. return [ a ];
  2235. } );
  2236. setTransformation( UnwrapOperation, SplitOperation, ( a, b ) => {
  2237. // Case 1:
  2238. //
  2239. // The element to unwrap got split, so now there are two elements to unwrap.
  2240. // This can be solved either by providing two unwrap operations or by reversing the split and applying the original unwrap.
  2241. //
  2242. if ( a.position.hasSameParentAs( b.position ) ) {
  2243. const reversed = b.getReversed();
  2244. // Merge operation (reversed split) always puts a node into a graveyard. Not every split operation pulls a node
  2245. // from the graveyard, though. This means that after reversing a split operation, there might be a need to
  2246. // update a position in graveyard.
  2247. if ( !b.graveyardPosition ) {
  2248. a.graveyardPosition = a.graveyardPosition._getTransformedByInsertion( reversed.graveyardPosition, 1 );
  2249. }
  2250. return [ reversed, a ];
  2251. }
  2252. // Case 2:
  2253. //
  2254. // The split element is the last element in unwrapped element. In this case, we need to manually modify
  2255. // `howMany` property because it wouldn't be correctly calculated by `_getTransformedBySplitOperation`.
  2256. //
  2257. if ( a.position.hasSameParentAs( b.insertionPosition ) ) {
  2258. a.howMany++;
  2259. return [ a ];
  2260. }
  2261. // The default case.
  2262. //
  2263. a.position = a.position._getTransformedBySplitOperation( b );
  2264. if ( b.graveyardPosition && b.graveyardPosition.hasSameParentAs( a.position ) ) {
  2265. a.howMany--;
  2266. }
  2267. a.graveyardPosition = a.graveyardPosition._getTransformedBySplitOperation( b );
  2268. return [ a ];
  2269. } );
  2270. setTransformation( UnwrapOperation, WrapOperation, ( a, b ) => {
  2271. // Case 1:
  2272. //
  2273. // Unwrapping an element that was in graveyard and was used to wrap nodes.
  2274. //
  2275. // Unwrap operation that unwraps in graveyard is a result of transformation of two same `UnwrapOperation`.
  2276. // Then `a` unwraps an element in graveyard and has `howMany` set to `0`. Now, the unwrap operation
  2277. // is going to be transformed by a wrap operation which undoes the previous operation. Operation `a` is
  2278. // in a state that is ready for this, but `howMany` has to be set again to a proper value.
  2279. //
  2280. if ( b.graveyardPosition && compareArrays( a.position.getParentPath(), b.graveyardPosition.path ) == 'same' ) {
  2281. a.howMany = b.howMany;
  2282. }
  2283. // The default case.
  2284. //
  2285. if ( a.position.hasSameParentAs( b.position ) ) {
  2286. a.howMany = a.howMany - b.howMany + 1;
  2287. }
  2288. a.position = a.position._getTransformedByWrapOperation( b );
  2289. a.graveyardPosition = a.graveyardPosition._getTransformedByWrapOperation( b );
  2290. return [ a ];
  2291. } );
  2292. setTransformation( UnwrapOperation, UnwrapOperation, ( a, b, context ) => {
  2293. // Case 1:
  2294. //
  2295. // Operations unwrap the same element.
  2296. //
  2297. // This situation is similar to `MergeOperation` x `MergeOperation` case. See it for more details.
  2298. //
  2299. if ( a.position.isEqual( b.position ) ) {
  2300. const path = b.graveyardPosition.path.slice();
  2301. path.push( 0 );
  2302. a.position = new Position( b.graveyardPosition.root, path );
  2303. a.howMany = 0;
  2304. a.graveyardPosition = Position.createFromPosition( b.graveyardPosition );
  2305. return [ a ];
  2306. }
  2307. // The default case.
  2308. //
  2309. a.position = a.position._getTransformedByUnwrapOperation( b );
  2310. if ( !a.graveyardPosition.isEqual( b.graveyardPosition ) || !context.aIsStrong ) {
  2311. a.graveyardPosition = a.graveyardPosition._getTransformedByUnwrapOperation( b );
  2312. }
  2313. return [ a ];
  2314. } );
  2315. // Checks whether `MoveOperation` `targetPosition` is inside a node from the moved range of the other `MoveOperation`.
  2316. //
  2317. // @private
  2318. // @param {module:engine/model/operation/moveoperation~MoveOperation} a
  2319. // @param {module:engine/model/operation/moveoperation~MoveOperation} b
  2320. // @returns {Boolean}
  2321. function _moveTargetIntoMovedRange( a, b ) {
  2322. return a.targetPosition._getTransformedByDeletion( b.sourcePosition, b.howMany ) === null;
  2323. }
  2324. // Helper function for `MoveOperation` x `MoveOperation` transformation. Converts given ranges and target position to
  2325. // move operations and returns them.
  2326. //
  2327. // Ranges and target position will be transformed on-the-fly when generating operations.
  2328. //
  2329. // Given `ranges` should be in the order of how they were in the original transformed operation.
  2330. //
  2331. // Given `targetPosition` is the target position of the first range from `ranges`.
  2332. //
  2333. // @private
  2334. // @param {Array.<module:engine/model/range~Range>} ranges
  2335. // @param {module:engine/model/position~Position} targetPosition
  2336. // @returns {Array.<module:engine/model/operation/moveoperation~MoveOperation>}
  2337. function _makeMoveOperationsFromRanges( ranges, targetPosition ) {
  2338. // At this moment we have some ranges and a target position, to which those ranges should be moved.
  2339. // Order in `ranges` array is the go-to order of after transformation.
  2340. //
  2341. // We are almost done. We have `ranges` and `targetPosition` to make operations from.
  2342. // Unfortunately, those operations may affect each other. Precisely, first operation after move
  2343. // may affect source range and target position of second and third operation. Same with second
  2344. // operation affecting third.
  2345. //
  2346. // We need to fix those source ranges and target positions once again, before converting `ranges` to operations.
  2347. const operations = [];
  2348. // Keep in mind that nothing will be transformed if there is just one range in `ranges`.
  2349. for ( let i = 0; i < ranges.length; i++ ) {
  2350. // Create new operation out of a range and target position.
  2351. const range = ranges[ i ];
  2352. const op = new MoveOperation( range.start, range.end.offset - range.start.offset, targetPosition, 0 );
  2353. operations.push( op );
  2354. // Transform other ranges by the generated operation.
  2355. for ( let j = i + 1; j < ranges.length; j++ ) {
  2356. // All ranges in `ranges` array should be:
  2357. //
  2358. // * non-intersecting (these are part of original operation source range), and
  2359. // * `targetPosition` does not target into them (opposite would mean that transformed operation targets "inside itself").
  2360. //
  2361. // This means that the transformation will be "clean" and always return one result.
  2362. ranges[ j ] = ranges[ j ]._getTransformedByMove( op.sourcePosition, op.targetPosition, op.howMany )[ 0 ];
  2363. }
  2364. targetPosition = targetPosition._getTransformedByMove( op.sourcePosition, op.targetPosition, op.howMany );
  2365. }
  2366. return operations;
  2367. }