8
0

position.js 19 KB

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