position.js 17 KB

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