8
0

basic-transformations.js 19 KB

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