position.js 20 KB

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