basic-transformations.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/delta/basic-transformations
  7. */
  8. import deltaTransform from './transform';
  9. const addTransformationCase = deltaTransform.addTransformationCase;
  10. const defaultTransform = deltaTransform.defaultTransform;
  11. import Range from '../range';
  12. import Position from '../position';
  13. import NoOperation from '../operation/nooperation';
  14. import AttributeOperation from '../operation/attributeoperation';
  15. import InsertOperation from '../operation/insertoperation';
  16. import ReinsertOperation from '../operation/reinsertoperation';
  17. import Delta from './delta';
  18. import AttributeDelta from './attributedelta';
  19. import InsertDelta from './insertdelta';
  20. import MarkerDelta from './markerdelta';
  21. import MergeDelta from './mergedelta';
  22. import MoveDelta from './movedelta';
  23. import SplitDelta from './splitdelta';
  24. import WeakInsertDelta from './weakinsertdelta';
  25. import WrapDelta from './wrapdelta';
  26. import UnwrapDelta from './unwrapdelta';
  27. import RenameDelta from './renamedelta';
  28. import RemoveDelta from './removedelta';
  29. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  30. // Provide transformations for default deltas.
  31. // Add special case for AttributeDelta x WeakInsertDelta transformation.
  32. addTransformationCase( AttributeDelta, WeakInsertDelta, ( a, b, context ) => {
  33. // If nodes are weak-inserted into attribute delta range, we need to apply changes from attribute delta on them.
  34. // So first we do the normal transformation and if this special cases happens, we will add an extra delta.
  35. const deltas = defaultTransform( a, b, context );
  36. if ( a.range.containsPosition( b.position ) ) {
  37. deltas.push( _getComplementaryAttrDelta( b, a ) );
  38. }
  39. return deltas;
  40. } );
  41. // Add special case for AttributeDelta x SplitDelta transformation.
  42. addTransformationCase( AttributeDelta, SplitDelta, ( a, b, context ) => {
  43. const splitPosition = new Position( b.position.root, b.position.path.slice( 0, -1 ) );
  44. const deltas = defaultTransform( a, b, context );
  45. for ( const operation of a.operations ) {
  46. // If a node that has been split has it's attribute updated, we should also update attribute of
  47. // the node created during splitting.
  48. if ( operation.range.containsPosition( splitPosition ) || operation.range.start.isEqual( splitPosition ) ) {
  49. const additionalAttributeDelta = new AttributeDelta();
  50. const rangeStart = splitPosition.getShiftedBy( 1 );
  51. const rangeEnd = Position.createFromPosition( rangeStart );
  52. rangeEnd.path.push( 0 );
  53. const oldValue = b._cloneOperation.nodes.getNode( 0 ).getAttribute( operation.key );
  54. additionalAttributeDelta.addOperation( new AttributeOperation(
  55. new Range( rangeStart, rangeEnd ),
  56. operation.key,
  57. oldValue === undefined ? null : oldValue,
  58. operation.newValue,
  59. 0
  60. ) );
  61. deltas.push( additionalAttributeDelta );
  62. break;
  63. }
  64. }
  65. return deltas;
  66. } );
  67. // Add special case for InsertDelta x MergeDelta transformation.
  68. addTransformationCase( InsertDelta, MergeDelta, ( a, b, context ) => {
  69. // If insert is applied at the same position where merge happened, we reverse the merge (we treat it like it
  70. // didn't happen) and then apply the original insert operation. This is "mirrored" in MergeDelta x InsertDelta
  71. // transformation below, where we simply do not apply MergeDelta.
  72. if ( a.position.isEqual( b.position ) ) {
  73. return [
  74. b.getReversed(),
  75. a.clone()
  76. ];
  77. }
  78. return defaultTransform( a, b, context );
  79. } );
  80. function transformMarkerDelta( a, b ) {
  81. const transformedDelta = a.clone();
  82. const transformedOp = transformedDelta.operations[ 0 ];
  83. if ( transformedOp.oldRange ) {
  84. transformedOp.oldRange = transformedOp.oldRange.getTransformedByDelta( b )[ 0 ];
  85. }
  86. if ( transformedOp.newRange ) {
  87. transformedOp.newRange = transformedOp.newRange.getTransformedByDelta( b )[ 0 ];
  88. }
  89. return [ transformedDelta ];
  90. }
  91. addTransformationCase( MarkerDelta, SplitDelta, transformMarkerDelta );
  92. addTransformationCase( MarkerDelta, MergeDelta, transformMarkerDelta );
  93. addTransformationCase( MarkerDelta, WrapDelta, transformMarkerDelta );
  94. addTransformationCase( MarkerDelta, UnwrapDelta, transformMarkerDelta );
  95. addTransformationCase( MarkerDelta, MoveDelta, transformMarkerDelta );
  96. addTransformationCase( MarkerDelta, RenameDelta, transformMarkerDelta );
  97. // Add special case for MoveDelta x MergeDelta transformation.
  98. addTransformationCase( MoveDelta, MergeDelta, ( a, b, context ) => {
  99. // If move delta is supposed to move a node that has been merged, we reverse the merge (we treat it like it
  100. // didn't happen) and then apply the original move operation. This is "mirrored" in MergeDelta x MoveDelta
  101. // transformation below, where we simply do not apply MergeDelta.
  102. const operateInSameParent =
  103. a.sourcePosition.root == b.position.root &&
  104. compareArrays( a.sourcePosition.getParentPath(), b.position.getParentPath() ) === 'same';
  105. const mergeInsideMoveRange = a.sourcePosition.offset <= b.position.offset && a.sourcePosition.offset + a.howMany > b.position.offset;
  106. if ( operateInSameParent && mergeInsideMoveRange ) {
  107. return [
  108. b.getReversed(),
  109. a.clone()
  110. ];
  111. }
  112. return defaultTransform( a, b, context );
  113. } );
  114. // Add special case for MergeDelta x InsertDelta transformation.
  115. addTransformationCase( MergeDelta, InsertDelta, ( a, b, context ) => {
  116. // If merge is applied at the same position where we inserted a range of nodes we cancel the merge as it's results
  117. // may be unexpected and very weird. Even if we do some "magic" we don't know what really are users' expectations.
  118. if ( a.position.isEqual( b.position ) ) {
  119. return [ noDelta() ];
  120. }
  121. return defaultTransform( a, b, context );
  122. } );
  123. // Add special case for MergeDelta x MoveDelta transformation.
  124. addTransformationCase( MergeDelta, MoveDelta, ( a, b, context ) => {
  125. // If merge is applied at the position between moved nodes we cancel the merge as it's results may be unexpected and
  126. // very weird. Even if we do some "magic" we don't know what really are users' expectations.
  127. const operateInSameParent =
  128. a.position.root == b.sourcePosition.root &&
  129. compareArrays( a.position.getParentPath(), b.sourcePosition.getParentPath() ) === 'same';
  130. const mergeInsideMoveRange = b.sourcePosition.offset <= a.position.offset && b.sourcePosition.offset + b.howMany > a.position.offset;
  131. if ( operateInSameParent && mergeInsideMoveRange ) {
  132. return [ noDelta() ];
  133. }
  134. return defaultTransform( a, b, context );
  135. } );
  136. // Add special case for SplitDelta x SplitDelta transformation.
  137. addTransformationCase( SplitDelta, SplitDelta, ( a, b, context ) => {
  138. const pathA = a.position.getParentPath();
  139. const pathB = b.position.getParentPath();
  140. // The special case is for splits inside the same parent.
  141. if ( a.position.root == b.position.root && compareArrays( pathA, pathB ) == 'same' ) {
  142. if ( a.position.offset == b.position.offset ) {
  143. // We are applying split at the position where split already happened. Additional split is not needed.
  144. return [ noDelta() ];
  145. } else if ( a.position.offset < b.position.offset ) {
  146. // Incoming split delta splits at closer offset. So we simply have to once again split the same node,
  147. // but since it was already split (at further offset) there are less child nodes in the split node.
  148. // This means that we have to update `howMany` parameter of `MoveOperation` for that delta.
  149. const delta = a.clone();
  150. delta._moveOperation.howMany = b.position.offset - a.position.offset;
  151. // If both SplitDeltas are taking their nodes from graveyard, we have to transform their ReinsertOperations.
  152. if (
  153. a._cloneOperation instanceof ReinsertOperation &&
  154. b._cloneOperation instanceof ReinsertOperation &&
  155. a._cloneOperation.sourcePosition.offset > b._cloneOperation.sourcePosition.offset
  156. ) {
  157. delta._cloneOperation.sourcePosition.offset--;
  158. }
  159. return [ delta ];
  160. } else {
  161. // Incoming split delta splits at further offset. We have to simulate that we are not splitting the
  162. // original split node but the node after it, which got created by the other split delta.
  163. // To do so, we increment offsets so it looks like the split delta was created in the next node.
  164. const delta = a.clone();
  165. delta._cloneOperation.position.offset++;
  166. delta._moveOperation.sourcePosition.path[ delta._moveOperation.sourcePosition.path.length - 2 ]++;
  167. delta._moveOperation.targetPosition.path[ delta._moveOperation.targetPosition.path.length - 2 ]++;
  168. delta._moveOperation.sourcePosition.offset = a.position.offset - b.position.offset;
  169. // If both SplitDeltas are taking their nodes from graveyard, we have to transform their ReinsertOperations.
  170. if (
  171. a._cloneOperation instanceof ReinsertOperation &&
  172. b._cloneOperation instanceof ReinsertOperation &&
  173. a._cloneOperation.sourcePosition.offset > b._cloneOperation.sourcePosition.offset
  174. ) {
  175. delta._cloneOperation.sourcePosition.offset--;
  176. }
  177. return [ delta ];
  178. }
  179. }
  180. return defaultTransform( a, b, context );
  181. } );
  182. // Add special case for SplitDelta x UnwrapDelta transformation.
  183. addTransformationCase( SplitDelta, UnwrapDelta, ( a, b, context ) => {
  184. // If incoming split delta tries to split a node that just got unwrapped, there is actually nothing to split,
  185. // so we discard that delta.
  186. if ( a.position.root == b.position.root && compareArrays( b.position.path, a.position.getParentPath() ) === 'same' ) {
  187. return [ noDelta() ];
  188. }
  189. return defaultTransform( a, b, context );
  190. } );
  191. // Add special case for SplitDelta x WrapDelta transformation.
  192. addTransformationCase( SplitDelta, WrapDelta, ( a, b, context ) => {
  193. // If split is applied at the position between wrapped nodes, we cancel the split as it's results may be unexpected and
  194. // very weird. Even if we do some "magic" we don't know what really are users' expectations.
  195. const sameRoot = a.position.root == b.range.start.root;
  196. const operateInSameParent = sameRoot && compareArrays( a.position.getParentPath(), b.range.start.getParentPath() ) === 'same';
  197. const splitInsideWrapRange = b.range.start.offset < a.position.offset && b.range.end.offset >= a.position.offset;
  198. if ( operateInSameParent && splitInsideWrapRange ) {
  199. return [ noDelta() ];
  200. } else if ( sameRoot && compareArrays( a.position.getParentPath(), b.range.end.getShiftedBy( -1 ).path ) === 'same' ) {
  201. // Split position is directly inside the last node from wrap range.
  202. // If that's the case, we manually change split delta so it will "target" inside the wrapping element.
  203. // By doing so we will be inserting split node right to the original node which feels natural and is a good UX.
  204. const delta = a.clone();
  205. // 1. Fix insert operation position.
  206. // Node to split is the last children of the wrapping element.
  207. // Wrapping element is the element inserted by WrapDelta (re)insert operation.
  208. // It is inserted after the wrapped range, but the wrapped range will be moved inside it.
  209. // Having this in mind, it is correct to use wrapped range start position as the position before wrapping element.
  210. const splitNodePos = Position.createFromPosition( b.range.start );
  211. // Now, `splitNodePos` points before wrapping element.
  212. // To get a position before last children of that element, we expand position's `path` member by proper offset.
  213. splitNodePos.path.push( b.howMany - 1 );
  214. // SplitDelta insert operation position should be right after the node we split.
  215. const insertPos = splitNodePos.getShiftedBy( 1 );
  216. delta._cloneOperation.position = insertPos;
  217. // 2. Fix move operation source position.
  218. // Nodes moved by SplitDelta will be moved from new position, modified by WrapDelta.
  219. // To obtain that new position, `splitNodePos` will be used, as this is the node we are extracting children from.
  220. const sourcePos = Position.createFromPosition( splitNodePos );
  221. // Nothing changed inside split node so it is correct to use the original split position offset.
  222. sourcePos.path.push( a.position.offset );
  223. delta._moveOperation.sourcePosition = sourcePos;
  224. // 3. Fix move operation target position.
  225. // SplitDelta move operation target position should be inside the node inserted by operation above.
  226. // Since the node is empty, we will insert at offset 0.
  227. const targetPos = Position.createFromPosition( insertPos );
  228. targetPos.path.push( 0 );
  229. delta._moveOperation.targetPosition = targetPos;
  230. return [ delta ];
  231. }
  232. return defaultTransform( a, b, context );
  233. } );
  234. // Add special case for SplitDelta x WrapDelta transformation.
  235. addTransformationCase( SplitDelta, AttributeDelta, ( a, b ) => {
  236. a = a.clone();
  237. const splitPosition = new Position( a.position.root, a.position.path.slice( 0, -1 ) );
  238. if ( a._cloneOperation instanceof InsertOperation ) {
  239. // If element to split had it's attribute changed, we have to reflect this change in an element
  240. // that is in SplitDelta's InsertOperation.
  241. for ( const operation of b.operations ) {
  242. if ( operation.range.containsPosition( splitPosition ) || operation.range.start.isEqual( splitPosition ) ) {
  243. if ( operation.newValue !== null ) {
  244. a._cloneOperation.nodes.getNode( 0 ).setAttribute( operation.key, operation.newValue );
  245. } else {
  246. a._cloneOperation.nodes.getNode( 0 ).removeAttribute( operation.key );
  247. }
  248. break;
  249. }
  250. }
  251. }
  252. return [ a ];
  253. } );
  254. // Add special case for UnwrapDelta x SplitDelta transformation.
  255. addTransformationCase( UnwrapDelta, SplitDelta, ( a, b, context ) => {
  256. // If incoming unwrap delta tries to unwrap node that got split we should unwrap the original node and the split copy.
  257. // This can be achieved either by reverting split and applying unwrap to singular node, or creating additional unwrap delta.
  258. if ( a.position.root == b.position.root && compareArrays( a.position.path, b.position.getParentPath() ) === 'same' ) {
  259. return [
  260. b.getReversed(),
  261. a.clone()
  262. ];
  263. }
  264. return defaultTransform( a, b, context );
  265. } );
  266. // Add special case for WeakInsertDelta x AttributeDelta transformation.
  267. addTransformationCase( WeakInsertDelta, AttributeDelta, ( a, b ) => {
  268. // If nodes are weak-inserted into attribute delta range, we need to apply changes from attribute delta on them.
  269. const deltas = [ a.clone() ];
  270. if ( b.range.containsPosition( a.position ) ) {
  271. deltas.push( _getComplementaryAttrDelta( a, b ) );
  272. }
  273. return deltas;
  274. } );
  275. // Add special case for WrapDelta x SplitDelta transformation.
  276. addTransformationCase( WrapDelta, SplitDelta, ( a, b, context ) => {
  277. // If incoming wrap delta tries to wrap range that contains split position, we have to cancel the split and apply
  278. // the wrap. Since split was already applied, we have to revert it.
  279. const sameRoot = a.range.start.root == b.position.root;
  280. const operateInSameParent = sameRoot && compareArrays( a.range.start.getParentPath(), b.position.getParentPath() ) === 'same';
  281. const splitInsideWrapRange = a.range.start.offset < b.position.offset && a.range.end.offset >= b.position.offset;
  282. if ( operateInSameParent && splitInsideWrapRange ) {
  283. return [
  284. b.getReversed(),
  285. a.clone()
  286. ];
  287. } else if ( sameRoot && compareArrays( b.position.getParentPath(), a.range.end.getShiftedBy( -1 ).path ) === 'same' ) {
  288. const delta = a.clone();
  289. // Move wrapping element insert position one node further so it is after the split node insertion.
  290. delta._insertOperation.position.offset++;
  291. // Include the split node copy.
  292. delta._moveOperation.howMany++;
  293. // Change the path to wrapping element in move operation.
  294. delta._moveOperation.targetPosition.path[ delta._moveOperation.targetPosition.path.length - 2 ]++;
  295. return [ delta ];
  296. }
  297. return defaultTransform( a, b, context );
  298. } );
  299. // Add special case for RenameDelta x SplitDelta transformation.
  300. addTransformationCase( RenameDelta, SplitDelta, ( a, b, context ) => {
  301. const splitPosition = new Position( b.position.root, b.position.path.slice( 0, -1 ) );
  302. const deltas = defaultTransform( a, b, context );
  303. if ( a.operations[ 0 ].position.isEqual( splitPosition ) ) {
  304. // If a node that has been split has it's name changed, we should also change name of
  305. // the node created during splitting.
  306. const additionalRenameDelta = a.clone();
  307. additionalRenameDelta.operations[ 0 ].position = a.operations[ 0 ].position.getShiftedBy( 1 );
  308. deltas.push( additionalRenameDelta );
  309. }
  310. return deltas;
  311. } );
  312. // Add special case for SplitDelta x RenameDelta transformation.
  313. addTransformationCase( SplitDelta, RenameDelta, ( a, b ) => {
  314. a = a.clone();
  315. const splitPosition = new Position( a.position.root, a.position.path.slice( 0, -1 ) );
  316. if ( a._cloneOperation instanceof InsertOperation ) {
  317. // If element to split had it's name changed, we have to reflect this change in an element
  318. // that is in SplitDelta's InsertOperation.
  319. if ( b.operations[ 0 ].position.isEqual( splitPosition ) ) {
  320. a._cloneOperation.nodes.getNode( 0 ).name = b.operations[ 0 ].newName;
  321. }
  322. }
  323. return [ a ];
  324. } );
  325. // Add special case for RemoveDelta x SplitDelta transformation.
  326. addTransformationCase( RemoveDelta, SplitDelta, ( a, b, context ) => {
  327. const deltas = defaultTransform( a, b, context );
  328. const insertPosition = b._cloneOperation.position;
  329. // In case if `defaultTransform` returned more than one delta.
  330. for ( const delta of deltas ) {
  331. for ( const operation of delta.operations ) {
  332. const rangeEnd = operation.sourcePosition.getShiftedBy( operation.howMany );
  333. if ( rangeEnd.isEqual( insertPosition ) ) {
  334. operation.howMany += 1;
  335. }
  336. }
  337. }
  338. return deltas;
  339. } );
  340. // Add special case for SplitDelta x RemoveDelta transformation.
  341. addTransformationCase( SplitDelta, RemoveDelta, ( a, b, context ) => {
  342. b = b.clone();
  343. const insertPosition = a._cloneOperation.position;
  344. for ( const operation of b.operations ) {
  345. const rangeEnd = operation.sourcePosition.getShiftedBy( operation.howMany );
  346. if ( rangeEnd.isEqual( insertPosition ) ) {
  347. operation.howMany += 1;
  348. }
  349. }
  350. return defaultTransform( a, b, context );
  351. } );
  352. // Helper function for `AttributeDelta` class transformations.
  353. // Creates an attribute delta that sets attribute from given `attributeDelta` on nodes from given `weakInsertDelta`.
  354. function _getComplementaryAttrDelta( weakInsertDelta, attributeDelta ) {
  355. const complementaryAttrDelta = new AttributeDelta();
  356. const nodes = weakInsertDelta.nodes;
  357. // At the beginning we store the attribute value from the first node on `weakInsertDelta` node list.
  358. let val = nodes.getNode( 0 ).getAttribute( attributeDelta.key );
  359. // This stores the last index of `weakInsertDelta` node list where the attribute value was different
  360. // than in the previous node. We need it to create separate `AttributeOperation`s for nodes with different attributes.
  361. let lastOffset = 0;
  362. // Sum of offsets of already processed nodes.
  363. let offsetSum = nodes.getNode( 0 ).offsetSize;
  364. for ( let i = 1; i < nodes.length; i++ ) {
  365. const node = nodes.getNode( i );
  366. const nodeAttrVal = node.getAttribute( attributeDelta.key );
  367. // If previous node has different attribute value, we will create an operation to the point before current node.
  368. // So all nodes with the same attributes up to this point will be included in one `AttributeOperation`.
  369. if ( nodeAttrVal != val ) {
  370. // New operation is created only when it is needed. If given node already has proper value for this
  371. // attribute we simply skip it without adding a new operation.
  372. if ( val != attributeDelta.value ) {
  373. addOperation();
  374. }
  375. val = nodeAttrVal;
  376. lastOffset = offsetSum;
  377. }
  378. offsetSum = offsetSum + node.offsetSize;
  379. }
  380. // At the end we have to add additional `AttributeOperation` for the last part of node list. If all nodes on the
  381. // node list had same attributes, this will be the only operation added to the delta.
  382. addOperation();
  383. return complementaryAttrDelta;
  384. function addOperation() {
  385. const range = new Range(
  386. weakInsertDelta.position.getShiftedBy( lastOffset ),
  387. weakInsertDelta.position.getShiftedBy( offsetSum )
  388. );
  389. const attrOperation = new AttributeOperation( range, attributeDelta.key, val, attributeDelta.value, 0 );
  390. complementaryAttrDelta.addOperation( attrOperation );
  391. }
  392. }
  393. // This is "no-op" delta, it has no type and only no-operation, it basically does nothing.
  394. // It is used when we don't want to apply changes but still we need to return a delta.
  395. function noDelta() {
  396. const noDelta = new Delta();
  397. // BaseVersion will be fixed later anyway.
  398. noDelta.addOperation( new NoOperation( 0 ) );
  399. return noDelta;
  400. }