position.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. CKEDITOR.define( [ 'treemodel/rootelement', 'utils', 'ckeditorerror' ], ( RootElement, utils, CKEditorError ) => {
  7. const SAME = 0;
  8. const AFTER = 1;
  9. const BEFORE = 2;
  10. const DIFFERENT = 3;
  11. /**
  12. * Position in the tree. Position is always located before or after a node.
  13. * See {@link #path} property for more information.
  14. *
  15. * @class treeModel.Position
  16. */
  17. class Position {
  18. /**
  19. * Creates a position.
  20. *
  21. * @param {treeModel.RootElement} root Root element for the path. Note that this element can not have a parent.
  22. * @param {Array.<Number>} path Position path. Must contain at least one item. See {@link #path} property for more information.
  23. * @constructor
  24. */
  25. constructor( root, path ) {
  26. if ( !( root instanceof RootElement ) ) {
  27. /**
  28. * Position root has to be an instance of RootElement.
  29. *
  30. * @error position-root-not-rootelement
  31. * @param root
  32. */
  33. throw new CKEditorError( 'position-root-not-rootelement: Position root has to be an instance of RootElement.', { root: root } );
  34. }
  35. /**
  36. * Root element for the path. Note that this element can not have a parent.
  37. *
  38. * @type {treeModel.RootElement}
  39. */
  40. this.root = root;
  41. if ( !( path instanceof Array ) || path.length === 0 ) {
  42. /**
  43. * Position path must be an Array with at least one item.
  44. *
  45. * @error position-path-incorrect
  46. * @param path
  47. */
  48. throw new CKEditorError( 'position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
  49. }
  50. /**
  51. * Position of the node it the tree. For example:
  52. *
  53. * root
  54. * |- p Before: [ 0 ] After: [ 1 ]
  55. * |- ul Before: [ 1 ] After: [ 2 ]
  56. * |- li Before: [ 1, 0 ] After: [ 1, 1 ]
  57. * | |- f Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
  58. * | |- o Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
  59. * | |- o Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
  60. * |- li Before: [ 1, 1 ] After: [ 1, 2 ]
  61. * |- b Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
  62. * |- a Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
  63. * |- r Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
  64. *
  65. * @type {Number[]}
  66. */
  67. this.path = path;
  68. }
  69. /**
  70. * Node directly after the position.
  71. *
  72. * @readonly
  73. * @property {treeModel.Node}
  74. */
  75. get nodeAfter() {
  76. return this.parent.getChild( this.offset ) || null;
  77. }
  78. /**
  79. * Node directly before the position.
  80. *
  81. * @readonly
  82. * @type {treeModel.Node}
  83. */
  84. get nodeBefore() {
  85. return this.parent.getChild( this.offset - 1 ) || null;
  86. }
  87. /**
  88. * Offset at which the position is located in the {@link #parent}.
  89. *
  90. * @readonly
  91. * @property {Number} offset
  92. */
  93. get offset() {
  94. return utils.last( this.path );
  95. }
  96. /**
  97. * Sets offset in the parent, which is the last element of the path.
  98. */
  99. set offset( newOffset ) {
  100. this.path[ this.path.length - 1 ] = newOffset;
  101. }
  102. /**
  103. * Parent element of the position. The position is located at {@link #offset} in this element.
  104. *
  105. * @readonly
  106. * @property {treeModel.Element} parent
  107. */
  108. get parent() {
  109. let parent = this.root;
  110. let i, len;
  111. for ( i = 0, len = this.path.length - 1; i < len; i++ ) {
  112. parent = parent.getChild( this.path[ i ] );
  113. }
  114. return parent;
  115. }
  116. /**
  117. * Creates and returns a new instance of {@link treeModel.Position}
  118. * which is equal to this {@link treeModel.Position position}.
  119. *
  120. * @returns {treeModel.Position} Cloned {@link treeModel.Position position}.
  121. */
  122. clone() {
  123. return new Position( this.root, this.path.slice() );
  124. }
  125. /**
  126. * Checks whether this position is before or after given position.
  127. *
  128. * @param {treeModel.Position} otherPosition Position to compare with.
  129. * @returns {Number} A flag indicating whether this position is {@link #BEFORE} or
  130. * {@link #AFTER} or {@link #SAME} as given position. If positions are in different roots,
  131. * {@link #DIFFERENT} flag is returned.
  132. */
  133. compareWith( otherPosition ) {
  134. if ( this.root != otherPosition.root ) {
  135. return DIFFERENT;
  136. }
  137. const result = utils.compareArrays( this.path, otherPosition.path );
  138. switch ( result ) {
  139. case utils.compareArrays.SAME:
  140. return SAME;
  141. case utils.compareArrays.PREFIX:
  142. return BEFORE;
  143. case utils.compareArrays.EXTENSION:
  144. return AFTER;
  145. default:
  146. if ( this.path[ result ] < otherPosition.path[ result ] ) {
  147. return BEFORE;
  148. } else {
  149. return AFTER;
  150. }
  151. }
  152. }
  153. /**
  154. * Returns the path to the parent, which is the {@link treeModel.Position#path} without the last element.
  155. *
  156. * This method returns the parent path even if the parent does not exists.
  157. *
  158. * @returns {Number[]} Path to the parent.
  159. */
  160. getParentPath() {
  161. return this.path.slice( 0, -1 );
  162. }
  163. /**
  164. * Returns this position after being updated by removing `howMany` nodes starting from `deletePosition`.
  165. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  166. *
  167. * @param {treeModel.Position} deletePosition Position before the first removed node.
  168. * @param {Number} howMany How many nodes are removed.
  169. * @returns {treeModel.Position|null} Transformed position or `null`.
  170. */
  171. getTransformedByDeletion( deletePosition, howMany ) {
  172. let transformed = this.clone();
  173. // This position can't be affected if deletion was in a different root.
  174. if ( this.root != deletePosition.root ) {
  175. return transformed;
  176. }
  177. if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.SAME ) {
  178. // If nodes are removed from the node that is pointed by this position...
  179. if ( deletePosition.offset < this.offset ) {
  180. // And are removed from before an offset of that position...
  181. // Decrement the offset accordingly.
  182. if ( deletePosition.offset + howMany > this.offset ) {
  183. transformed.offset = deletePosition.offset;
  184. } else {
  185. transformed.offset -= howMany;
  186. }
  187. }
  188. } else if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.PREFIX ) {
  189. // If nodes are removed from a node that is on a path to this position...
  190. const i = deletePosition.path.length - 1;
  191. if ( deletePosition.offset < this.path[ i ] ) {
  192. // And are removed from before next node of that path...
  193. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  194. // If the next node of that path is removed return null
  195. // because the node containing this position got removed.
  196. return null;
  197. } else {
  198. // Otherwise, decrement index on that path.
  199. transformed.path[ i ] -= howMany;
  200. }
  201. }
  202. }
  203. return transformed;
  204. }
  205. /**
  206. * Returns this position after being updated by inserting `howMany` nodes at `insertPosition`.
  207. *
  208. * @param {treeModel.Position} insertPosition Position where nodes are inserted.
  209. * @param {Number} howMany How many nodes are inserted.
  210. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  211. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  212. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  213. * @returns {treeModel.Position} Transformed position.
  214. */
  215. getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  216. let transformed = this.clone();
  217. // This position can't be affected if insertion was in a different root.
  218. if ( this.root != insertPosition.root ) {
  219. return transformed;
  220. }
  221. if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.SAME ) {
  222. // If nodes are inserted in the node that is pointed by this position...
  223. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  224. // And are inserted before an offset of that position...
  225. // "Push" this positions offset.
  226. transformed.offset += howMany;
  227. }
  228. } else if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == utils.compareArrays.PREFIX ) {
  229. // If nodes are inserted in a node that is on a path to this position...
  230. const i = insertPosition.path.length - 1;
  231. if ( insertPosition.offset <= this.path[ i ] ) {
  232. // And are inserted before next node of that path...
  233. // "Push" the index on that path.
  234. transformed.path[ i ] += howMany;
  235. }
  236. }
  237. return transformed;
  238. }
  239. /**
  240. * Returns this position after being updated by moving `howMany` attributes from `sourcePosition` to `targetPosition`.
  241. *
  242. * @param {treeModel.Position} sourcePosition Position before the first element to move.
  243. * @param {treeModel.Position} targetPosition Position where moved elements will be inserted.
  244. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  245. * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
  246. * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
  247. * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
  248. * @returns {treeModel.Position} Transformed position.
  249. */
  250. getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore ) {
  251. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  252. let transformed = this.getTransformedByDeletion( sourcePosition, howMany );
  253. if ( transformed !== null ) {
  254. // This position is not inside a removed node.
  255. // Next step is to reflect pasting nodes, which might further affect the position.
  256. transformed = transformed.getTransformedByInsertion( targetPosition, howMany, insertBefore );
  257. } else {
  258. // This position is inside a removed node. In this case, we are unable to simply transform it by range insertion.
  259. // Instead, we calculate a combination of this position, move source position and target position.
  260. transformed = this._getCombined( sourcePosition, targetPosition );
  261. }
  262. return transformed;
  263. }
  264. /**
  265. * Checks whether this position is after given position.
  266. *
  267. * **Note:** see {treeModel.Position#isBefore}.
  268. *
  269. * @param {treeModel.Position} otherPosition Position to compare with.
  270. * @returns {Boolean} True if this position is after given position.
  271. */
  272. isAfter( otherPosition ) {
  273. return this.compareWith( otherPosition ) == AFTER;
  274. }
  275. /**
  276. * Checks whether this position is before given position.
  277. *
  278. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  279. * be `true` if positions are in different roots and you might not expect this. You should probably use
  280. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  281. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  282. *
  283. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  284. * // do A.
  285. * } else {
  286. * // do B.
  287. * }
  288. *
  289. * or, if you have only one if-branch:
  290. *
  291. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  292. * // do B.
  293. * }
  294. *
  295. * rather than:
  296. *
  297. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  298. * // do B.
  299. * } else {
  300. * // do A.
  301. * }
  302. *
  303. * @param {treeModel.Position} otherPosition Position to compare with.
  304. * @returns {Boolean} True if this position is before given position.
  305. */
  306. isBefore( otherPosition ) {
  307. return this.compareWith( otherPosition ) == BEFORE;
  308. }
  309. /**
  310. * Checks whether this position equals given position.
  311. *
  312. * @param {treeModel.Position} otherPosition Position to compare with.
  313. * @returns {Boolean} True if positions are same.
  314. */
  315. isEqual( otherPosition ) {
  316. return this.compareWith( otherPosition ) == SAME;
  317. }
  318. /**
  319. * Creates a new position after given node.
  320. *
  321. * @param {treeModel.Node} node Node the position should be directly after.
  322. * @returns {treeModel.Position}
  323. */
  324. static createAfter( node ) {
  325. if ( !node.parent ) {
  326. /**
  327. * You can not make position after root.
  328. *
  329. * @error position-after-root
  330. * @param {treeModel.Node} root
  331. */
  332. throw new CKEditorError( 'position-after-root: You can not make position after root.', { root: node } );
  333. }
  334. return Position.createFromParentAndOffset( node.parent, node.getIndex() + 1 );
  335. }
  336. /**
  337. * Creates a new position before the given node.
  338. *
  339. * @param {treeModel.node} node Node the position should be directly before.
  340. * @returns {treeModel.Position}
  341. */
  342. static createBefore( node ) {
  343. if ( !node.parent ) {
  344. /**
  345. * You can not make position before root.
  346. *
  347. * @error position-before-root
  348. * @param {treeModel.Node} root
  349. */
  350. throw new CKEditorError( 'position-before-root: You can not make position before root.', { root: node } );
  351. }
  352. return Position.createFromParentAndOffset( node.parent, node.getIndex() );
  353. }
  354. /**
  355. * Creates a new position from the parent element and the offset in that element.
  356. *
  357. * @param {treeModel.Element} parent Position parent element.
  358. * @param {Number} offset Position offset.
  359. * @returns {treeModel.Position}
  360. */
  361. static createFromParentAndOffset( parent, offset ) {
  362. const path = parent.getPath();
  363. path.push( offset );
  364. return new Position( parent.root, path );
  365. }
  366. /**
  367. * Returns a new position that is a combination of this position and given positions. The combined
  368. * position is this position transformed by moving a range starting at `from` to `to` position.
  369. * It is expected that this position is inside the moved range.
  370. *
  371. * In other words, this method in a smart way "cuts out" `source` path from this position and
  372. * injects `target` path in it's place, while doing necessary fixes in order to get a correct path.
  373. *
  374. * Example:
  375. *
  376. * let original = new Position( root, [ 2, 3, 1 ] );
  377. * let source = new Position( root, [ 2, 2 ] );
  378. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  379. * let combined = original.getCombined( source, target );
  380. * // combined.path is [ 1, 1, 4, 1 ], combined.root is otherRoot
  381. *
  382. * Explanation:
  383. *
  384. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  385. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  386. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  387. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  388. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  389. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  390. *
  391. * @protected
  392. * @param {treeModel.Position} source Beginning of the moved range.
  393. * @param {treeModel.Position} target Position where the range is moved.
  394. * @returns {treeModel.Position} Combined position.
  395. */
  396. _getCombined( source, target ) {
  397. const i = source.path.length - 1;
  398. // The first part of a path to combined position is a path to the place where nodes were moved.
  399. let combined = target.clone();
  400. // Then we have to update the rest of the path.
  401. // Fix the offset because this position might be after `from` position and we have to reflect that.
  402. combined.offset = combined.offset + this.path[ i ] - source.offset;
  403. // Then, add the rest of the path.
  404. // If this position is at the same level as `from` position nothing will get added.
  405. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  406. return combined;
  407. }
  408. }
  409. /**
  410. * Flag for "is after" relation between Positions.
  411. *
  412. * @type {Number}
  413. */
  414. Position.AFTER = AFTER;
  415. /**
  416. * Flag for "is before" relation between Positions.
  417. *
  418. * @type {Number}
  419. */
  420. Position.BEFORE = BEFORE;
  421. /**
  422. * Flag for "are in different roots" relation between Positions.
  423. *
  424. * @type {Number}
  425. */
  426. Position.DIFFERENT = DIFFERENT;
  427. /**
  428. * Flag for "are same" relation between Positions.
  429. *
  430. * @type {Number}
  431. */
  432. Position.SAME = SAME;
  433. return Position;
  434. } );