8
0

basic-transformations.js 21 KB

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