position.js 16 KB

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