8
0

position.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. * A flag indicating whether this position is `'BEFORE'` or `'AFTER'` or `'SAME'` as given position.
  12. * If positions are in different roots `'DIFFERENT'` flag is returned.
  13. *
  14. * @typedef {String} treeModel.PositionRelation
  15. */
  16. /**
  17. * Position in the tree. Position is always located before or after a node.
  18. * See {@link #path} property for more information.
  19. *
  20. * @class treeModel.Position
  21. */
  22. export default class Position {
  23. /**
  24. * Creates a position.
  25. *
  26. * @param {treeModel.RootElement} root Root element for the path. Note that this element can not have a parent.
  27. * @param {Array.<Number>} path Position path. Must contain at least one item. See {@link #path} property for more information.
  28. * @constructor
  29. */
  30. constructor( root, path ) {
  31. if ( !( root instanceof RootElement ) ) {
  32. /**
  33. * Position root has to be an instance of RootElement.
  34. *
  35. * @error position-root-not-rootelement
  36. * @param root
  37. */
  38. throw new CKEditorError( 'position-root-not-rootelement: Position root has to be an instance of RootElement.', { root: root } );
  39. }
  40. /**
  41. * Root element for the path. Note that this element can not have a parent.
  42. *
  43. * @type {treeModel.RootElement}
  44. */
  45. this.root = root;
  46. if ( !( path instanceof Array ) || path.length === 0 ) {
  47. /**
  48. * Position path must be an Array with at least one item.
  49. *
  50. * @error position-path-incorrect
  51. * @param path
  52. */
  53. throw new CKEditorError( 'position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
  54. }
  55. /**
  56. * Position of the node it the tree. For example:
  57. *
  58. * root
  59. * |- p Before: [ 0 ] After: [ 1 ]
  60. * |- ul Before: [ 1 ] After: [ 2 ]
  61. * |- li Before: [ 1, 0 ] After: [ 1, 1 ]
  62. * | |- f Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
  63. * | |- o Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
  64. * | |- o Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
  65. * |- li Before: [ 1, 1 ] After: [ 1, 2 ]
  66. * |- b Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
  67. * |- a Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
  68. * |- r Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
  69. *
  70. * @type {Number[]}
  71. */
  72. this.path = path;
  73. }
  74. /**
  75. * Node directly after the position.
  76. *
  77. * @readonly
  78. * @property {treeModel.Node}
  79. */
  80. get nodeAfter() {
  81. return this.parent.getChild( this.offset ) || null;
  82. }
  83. /**
  84. * Node directly before the position.
  85. *
  86. * @readonly
  87. * @type {treeModel.Node}
  88. */
  89. get nodeBefore() {
  90. return this.parent.getChild( this.offset - 1 ) || null;
  91. }
  92. /**
  93. * Offset at which the position is located in the {@link #parent}.
  94. *
  95. * @readonly
  96. * @property {Number} offset
  97. */
  98. get offset() {
  99. return last( this.path );
  100. }
  101. /**
  102. * Sets offset in the parent, which is the last element of the path.
  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. * @property {treeModel.Element} parent
  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 {treeModel.Position} otherPosition Position to compare with.
  125. * @returns {treeModel.PositionRelation}
  126. */
  127. compareWith( otherPosition ) {
  128. if ( this.root != otherPosition.root ) {
  129. return 'DIFFERENT';
  130. }
  131. const result = utils.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 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 {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. * @param {treeModel.Position} deletePosition Position before the first removed node.
  174. * @param {Number} howMany How many nodes are removed.
  175. * @returns {treeModel.Position|null} Transformed position or `null`.
  176. */
  177. getTransformedByDeletion( deletePosition, howMany ) {
  178. let transformed = Position.createFromPosition( this );
  179. // This position can't be affected if deletion was in a different root.
  180. if ( this.root != deletePosition.root ) {
  181. return transformed;
  182. }
  183. if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'SAME' ) {
  184. // If nodes are removed from the node that is pointed by this position...
  185. if ( deletePosition.offset < this.offset ) {
  186. // And are removed from before an offset of that position...
  187. // Decrement the offset accordingly.
  188. if ( deletePosition.offset + howMany > this.offset ) {
  189. transformed.offset = deletePosition.offset;
  190. } else {
  191. transformed.offset -= howMany;
  192. }
  193. }
  194. } else if ( utils.compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'PREFIX' ) {
  195. // If nodes are removed from a node that is on a path to this position...
  196. const i = deletePosition.path.length - 1;
  197. if ( deletePosition.offset < this.path[ i ] ) {
  198. // And are removed from before next node of that path...
  199. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  200. // If the next node of that path is removed return null
  201. // because the node containing this position got removed.
  202. return null;
  203. } else {
  204. // Otherwise, decrement index on that path.
  205. transformed.path[ i ] -= howMany;
  206. }
  207. }
  208. }
  209. return transformed;
  210. }
  211. /**
  212. * Returns this position after being updated by inserting `howMany` nodes at `insertPosition`.
  213. *
  214. * @param {treeModel.Position} insertPosition Position where nodes are inserted.
  215. * @param {Number} howMany How many nodes are inserted.
  216. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  217. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  218. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  219. * @returns {treeModel.Position} Transformed position.
  220. */
  221. getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  222. let transformed = Position.createFromPosition( this );
  223. // This position can't be affected if insertion was in a different root.
  224. if ( this.root != insertPosition.root ) {
  225. return transformed;
  226. }
  227. if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'SAME' ) {
  228. // If nodes are inserted in the node that is pointed by this position...
  229. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  230. // And are inserted before an offset of that position...
  231. // "Push" this positions offset.
  232. transformed.offset += howMany;
  233. }
  234. } else if ( utils.compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'PREFIX' ) {
  235. // If nodes are inserted in a node that is on a path to this position...
  236. const i = insertPosition.path.length - 1;
  237. if ( insertPosition.offset <= this.path[ i ] ) {
  238. // And are inserted before next node of that path...
  239. // "Push" the index on that path.
  240. transformed.path[ i ] += howMany;
  241. }
  242. }
  243. return transformed;
  244. }
  245. /**
  246. * Returns this position after being updated by moving `howMany` attributes from `sourcePosition` to `targetPosition`.
  247. *
  248. * @param {treeModel.Position} sourcePosition Position before the first element to move.
  249. * @param {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. * @returns {treeModel.Position} Transformed position.
  255. */
  256. getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore ) {
  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 ) {
  260. // This position is not inside a removed node.
  261. // Next step is to reflect pasting nodes, which might further affect the position.
  262. transformed = transformed.getTransformedByInsertion( targetPosition, howMany, insertBefore );
  263. } else {
  264. // This position is inside a removed node. In this case, we are unable to simply transform it by range insertion.
  265. // Instead, we calculate a combination of this position, move source position and target position.
  266. transformed = this._getCombined( sourcePosition, targetPosition );
  267. }
  268. return transformed;
  269. }
  270. /**
  271. * Checks whether this position is after given position.
  272. *
  273. * **Note:** see {treeModel.Position#isBefore}.
  274. *
  275. * @param {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 {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 {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 {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. * @param {treeModel.Node} node Node the position should be directly after.
  372. * @returns {treeModel.Position}
  373. */
  374. static createAfter( node ) {
  375. if ( !node.parent ) {
  376. /**
  377. * You can not make position after root.
  378. *
  379. * @error position-after-root
  380. * @param {treeModel.Node} root
  381. */
  382. throw new CKEditorError( 'position-after-root: You can not make position after root.', { root: node } );
  383. }
  384. return this.createFromParentAndOffset( node.parent, node.getIndex() + 1 );
  385. }
  386. /**
  387. * Creates a new position before the given node.
  388. *
  389. * @param {treeModel.node} node Node the position should be directly before.
  390. * @returns {treeModel.Position}
  391. */
  392. static createBefore( node ) {
  393. if ( !node.parent ) {
  394. /**
  395. * You can not make position before root.
  396. *
  397. * @error position-before-root
  398. * @param {treeModel.Node} root
  399. */
  400. throw new CKEditorError( 'position-before-root: You can not make position before root.', { root: node } );
  401. }
  402. return this.createFromParentAndOffset( node.parent, node.getIndex() );
  403. }
  404. /**
  405. * Creates a new position from the parent element and the offset in that element.
  406. *
  407. * @param {treeModel.Element} parent Position parent element.
  408. * @param {Number} offset Position offset.
  409. * @returns {treeModel.Position}
  410. */
  411. static createFromParentAndOffset( parent, offset ) {
  412. const path = parent.getPath();
  413. path.push( offset );
  414. return new this( parent.root, path );
  415. }
  416. /**
  417. * Creates and returns a new instance of Position, which is equal to passed position.
  418. *
  419. * @param {treeModel.Position} position Position to be cloned.
  420. * @returns {treeModel.Position}
  421. */
  422. static createFromPosition( position ) {
  423. return new this( position.root, position.path.slice() );
  424. }
  425. /**
  426. * Returns a new position that is a combination of this position and given positions. The combined
  427. * position is this position transformed by moving a range starting at `from` to `to` position.
  428. * It is expected that this position is inside the moved range.
  429. *
  430. * In other words, this method in a smart way "cuts out" `source` path from this position and
  431. * injects `target` path in it's place, while doing necessary fixes in order to get a correct path.
  432. *
  433. * Example:
  434. *
  435. * let original = new Position( root, [ 2, 3, 1 ] );
  436. * let source = new Position( root, [ 2, 2 ] );
  437. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  438. * let combined = original.getCombined( source, target );
  439. * // combined.path is [ 1, 1, 4, 1 ], combined.root is otherRoot
  440. *
  441. * Explanation:
  442. *
  443. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  444. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  445. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  446. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  447. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  448. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  449. *
  450. * @protected
  451. * @param {treeModel.Position} source Beginning of the moved range.
  452. * @param {treeModel.Position} target Position where the range is moved.
  453. * @returns {treeModel.Position} Combined position.
  454. */
  455. _getCombined( source, target ) {
  456. const i = source.path.length - 1;
  457. // The first part of a path to combined position is a path to the place where nodes were moved.
  458. let combined = Position.createFromPosition( target );
  459. // Then we have to update the rest of the path.
  460. // Fix the offset because this position might be after `from` position and we have to reflect that.
  461. combined.offset = combined.offset + this.path[ i ] - source.offset;
  462. // Then, add the rest of the path.
  463. // If this position is at the same level as `from` position nothing will get added.
  464. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  465. return combined;
  466. }
  467. }