8
0

position.js 18 KB

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