position.js 18 KB

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