position.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/position
  7. */
  8. import DocumentFragment from './documentfragment';
  9. import Element from './element';
  10. import TreeWalker from './treewalker';
  11. import last from '@ckeditor/ckeditor5-utils/src/lib/lodash/last';
  12. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  13. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  14. import Text from './text';
  15. /**
  16. * Represents a position in the model tree.
  17. *
  18. * **Note:** Position is based on offsets, not indexes. This means that position in element containing two text nodes
  19. * with data `foo` and `bar`, position between them has offset `3`, not `1`.
  20. * See {@link module:engine/model/position~Position#path} for more.
  21. *
  22. * Since position in a model is represented by a {@link module:engine/model/position~Position#root position root} and
  23. * {@link module:engine/model/position~Position#path position path} it is possible to create positions placed in non-existing elements.
  24. * This requirement is important for {@link module:engine/model/operation/transform~transform operational transformation}.
  25. *
  26. * Also, {@link module:engine/model/operation/operation~Operation operations}
  27. * kept in {@link module:engine/model/document~Document#history document history}
  28. * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
  29. * after document got changed.
  30. *
  31. * When changes are applied to model, it may also happen that {@link module:engine/model/position~Position#parent position parent}
  32. * will change even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
  33. * {@link module:engine/model/position~Position#parent} and some other properties and methods will throw errors.
  34. *
  35. * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
  36. */
  37. export default class Position {
  38. /**
  39. * Creates a position.
  40. *
  41. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  42. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  43. */
  44. constructor( root, path ) {
  45. if ( !( root instanceof Element ) && !( root instanceof DocumentFragment ) ) {
  46. /**
  47. * Position root invalid.
  48. *
  49. * @error position-root-invalid.
  50. */
  51. throw new CKEditorError( 'model-position-root-invalid: Position root invalid.' );
  52. }
  53. if ( !( path instanceof Array ) || path.length === 0 ) {
  54. /**
  55. * Position path must be an Array with at least one item.
  56. *
  57. * @error position-path-incorrect
  58. * @param path
  59. */
  60. throw new CKEditorError( 'model-position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
  61. }
  62. // Normalize the root and path (if element was passed).
  63. path = root.getPath().concat( path );
  64. root = root.root;
  65. /**
  66. * Root of the position path.
  67. *
  68. * @readonly
  69. * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  70. * module:engine/model/position~Position#root
  71. */
  72. this.root = root;
  73. /**
  74. * Position of the node it the tree. Path is described through offsets, not indexes.
  75. *
  76. * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
  77. * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
  78. * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
  79. * down to the position offset in it's parent.
  80. *
  81. * ROOT
  82. * |- P before: [ 0 ] after: [ 1 ]
  83. * |- UL before: [ 1 ] after: [ 2 ]
  84. * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
  85. * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
  86. * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
  87. * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
  88. *
  89. * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
  90. * greater than `1` you can place position offset between their start and end:
  91. *
  92. * ROOT
  93. * |- P
  94. * |- UL
  95. * |- LI
  96. * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
  97. * |- LI
  98. * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
  99. *
  100. * @member {Array.<Number>} module:engine/model/position~Position#path
  101. */
  102. this.path = path;
  103. }
  104. /**
  105. * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
  106. * to the last item in position {@link module:engine/model/position~Position#path path}.
  107. *
  108. * @type {Number}
  109. */
  110. get offset() {
  111. return last( this.path );
  112. }
  113. /**
  114. * @param {Number} newOffset
  115. */
  116. set offset( newOffset ) {
  117. this.path[ this.path.length - 1 ] = newOffset;
  118. }
  119. /**
  120. * Parent element of this position.
  121. *
  122. * Keep in mind that `parent` value is calculated when the property is accessed.
  123. * If {@link module:engine/model/position~Position#path position path}
  124. * leads to a non-existing element, `parent` property will throw error.
  125. *
  126. * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
  127. *
  128. * @readonly
  129. * @type {module:engine/model/element~Element}
  130. */
  131. get parent() {
  132. let parent = this.root;
  133. for ( let i = 0; i < this.path.length - 1; i++ ) {
  134. parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
  135. }
  136. return parent;
  137. }
  138. /**
  139. * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
  140. * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
  141. * in text node, position index is equal to the index of that text node.
  142. *
  143. * @readonly
  144. * @type {Number}
  145. */
  146. get index() {
  147. return this.parent.offsetToIndex( this.offset );
  148. }
  149. /**
  150. * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
  151. * position is not in a text node.
  152. *
  153. * @readonly
  154. * @type {module:engine/model/text~Text|null}
  155. */
  156. get textNode() {
  157. let node = this.parent.getChild( this.index );
  158. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  159. }
  160. /**
  161. * Node directly after this position or `null` if this position is in text node.
  162. *
  163. * @readonly
  164. * @type {module:engine/model/node~Node|null}
  165. */
  166. get nodeAfter() {
  167. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  168. }
  169. /**
  170. * Node directly before this position or `null` if this position is in text node.
  171. *
  172. * @readonly
  173. * @type {Node}
  174. */
  175. get nodeBefore() {
  176. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  177. }
  178. /**
  179. * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  180. *
  181. * @readonly
  182. * @type {Boolean}
  183. */
  184. get isAtStart() {
  185. return this.offset === 0;
  186. }
  187. /**
  188. * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  189. *
  190. * @readonly
  191. * @type {Boolean}
  192. */
  193. get isAtEnd() {
  194. return this.offset == this.parent.maxOffset;
  195. }
  196. /**
  197. * Checks whether this position is before or after given position.
  198. *
  199. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  200. * @returns {module:engine/model/position~PositionRelation}
  201. */
  202. compareWith( otherPosition ) {
  203. if ( this.root != otherPosition.root ) {
  204. return 'different';
  205. }
  206. const result = compareArrays( this.path, otherPosition.path );
  207. switch ( result ) {
  208. case 'same':
  209. return 'same';
  210. case 'prefix':
  211. return 'before';
  212. case 'extension':
  213. return 'after';
  214. default:
  215. if ( this.path[ result ] < otherPosition.path[ result ] ) {
  216. return 'before';
  217. } else {
  218. return 'after';
  219. }
  220. }
  221. }
  222. /**
  223. * Gets the farthest position which matches the callback using
  224. * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
  225. *
  226. * For example:
  227. *
  228. * getLastMatchingPosition( value => value.type == 'text' );
  229. * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
  230. *
  231. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
  232. * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
  233. *
  234. * getLastMatchingPosition( value => false );
  235. * // Do not move the position.
  236. *
  237. * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
  238. * return `true` if the value should be skipped or `false` if not.
  239. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  240. *
  241. * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
  242. */
  243. getLastMatchingPosition( skip, options = {} ) {
  244. options.startPosition = this;
  245. const treeWalker = new TreeWalker( options );
  246. treeWalker.skip( skip );
  247. return treeWalker.position;
  248. }
  249. /**
  250. * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
  251. * but without the last item.
  252. *
  253. * This method returns the parent path even if the parent does not exists.
  254. *
  255. * @returns {Array.<Number>} Path to the parent.
  256. */
  257. getParentPath() {
  258. return this.path.slice( 0, -1 );
  259. }
  260. /**
  261. * Returns ancestors array of this position, that is this position's parent and its ancestors.
  262. *
  263. * @returns {Array.<module:engine/model/item~Item>} Array with ancestors.
  264. */
  265. getAncestors() {
  266. if ( this.parent instanceof DocumentFragment ) {
  267. return [ this.parent ];
  268. } else {
  269. return this.parent.getAncestors( { includeNode: true } );
  270. }
  271. }
  272. /**
  273. * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
  274. * of these two paths must be identical.
  275. *
  276. * @param {module:engine/model/position~Position} position The second position.
  277. * @returns {Array.<Number>} The common path.
  278. */
  279. getCommonPath( position ) {
  280. if ( this.root != position.root ) {
  281. return [];
  282. }
  283. // We find on which tree-level start and end have the lowest common ancestor
  284. let cmp = compareArrays( this.path, position.path );
  285. // If comparison returned string it means that arrays are same.
  286. let diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
  287. return this.path.slice( 0, diffAt );
  288. }
  289. /**
  290. * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
  291. * is shifted by `shift` value (can be a negative value).
  292. *
  293. * @param {Number} shift Offset shift. Can be a negative value.
  294. * @returns {module:engine/model/position~Position} Shifted position.
  295. */
  296. getShiftedBy( shift ) {
  297. let shifted = Position.createFromPosition( this );
  298. let offset = shifted.offset + shift;
  299. shifted.offset = offset < 0 ? 0 : offset;
  300. return shifted;
  301. }
  302. /**
  303. * Checks whether this position is after given position.
  304. *
  305. * @see module:engine/model/position~Position#isBefore
  306. *
  307. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  308. * @returns {Boolean} True if this position is after given position.
  309. */
  310. isAfter( otherPosition ) {
  311. return this.compareWith( otherPosition ) == 'after';
  312. }
  313. /**
  314. * Checks whether this position is before given position.
  315. *
  316. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  317. * be `true` if positions are in different roots and you might not expect this. You should probably use
  318. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  319. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  320. *
  321. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  322. * // do A.
  323. * } else {
  324. * // do B.
  325. * }
  326. *
  327. * or, if you have only one if-branch:
  328. *
  329. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  330. * // do B.
  331. * }
  332. *
  333. * rather than:
  334. *
  335. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  336. * // do B.
  337. * } else {
  338. * // do A.
  339. * }
  340. *
  341. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  342. * @returns {Boolean} True if this position is before given position.
  343. */
  344. isBefore( otherPosition ) {
  345. return this.compareWith( otherPosition ) == 'before';
  346. }
  347. /**
  348. * Checks whether this position is equal to given position.
  349. *
  350. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  351. * @returns {Boolean} True if positions are same.
  352. */
  353. isEqual( otherPosition ) {
  354. return this.compareWith( otherPosition ) == 'same';
  355. }
  356. /**
  357. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  358. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  359. * they are very similar or even indistinguishable.
  360. *
  361. * **Note:** this method traverses model document so it can be only used when range is up-to-date with model document.
  362. *
  363. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  364. * @returns {Boolean} True if positions touch.
  365. */
  366. isTouching( otherPosition ) {
  367. let left = null;
  368. let right = null;
  369. let compare = this.compareWith( otherPosition );
  370. switch ( compare ) {
  371. case 'same':
  372. return true;
  373. case 'before':
  374. left = Position.createFromPosition( this );
  375. right = Position.createFromPosition( otherPosition );
  376. break;
  377. case 'after':
  378. left = Position.createFromPosition( otherPosition );
  379. right = Position.createFromPosition( this );
  380. break;
  381. default:
  382. return false;
  383. }
  384. // Cached for optimization purposes.
  385. let leftParent = left.parent;
  386. while ( left.path.length + right.path.length ) {
  387. if ( left.isEqual( right ) ) {
  388. return true;
  389. }
  390. if ( left.path.length > right.path.length ) {
  391. if ( left.offset !== leftParent.maxOffset ) {
  392. return false;
  393. }
  394. left.path = left.path.slice( 0, -1 );
  395. leftParent = leftParent.parent;
  396. left.offset++;
  397. } else {
  398. if ( right.offset !== 0 ) {
  399. return false;
  400. }
  401. right.path = right.path.slice( 0, -1 );
  402. }
  403. }
  404. }
  405. /**
  406. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  407. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  408. *
  409. * @protected
  410. * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
  411. * @param {Number} howMany How many nodes are removed.
  412. * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
  413. */
  414. _getTransformedByDeletion( deletePosition, howMany ) {
  415. let transformed = Position.createFromPosition( this );
  416. // This position can't be affected if deletion was in a different root.
  417. if ( this.root != deletePosition.root ) {
  418. return transformed;
  419. }
  420. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  421. // If nodes are removed from the node that is pointed by this position...
  422. if ( deletePosition.offset < this.offset ) {
  423. // And are removed from before an offset of that position...
  424. if ( deletePosition.offset + howMany > this.offset ) {
  425. // Position is in removed range, it's no longer in the tree.
  426. return null;
  427. } else {
  428. // Decrement the offset accordingly.
  429. transformed.offset -= howMany;
  430. }
  431. }
  432. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  433. // If nodes are removed from a node that is on a path to this position...
  434. const i = deletePosition.path.length - 1;
  435. if ( deletePosition.offset <= this.path[ i ] ) {
  436. // And are removed from before next node of that path...
  437. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  438. // If the next node of that path is removed return null
  439. // because the node containing this position got removed.
  440. return null;
  441. } else {
  442. // Otherwise, decrement index on that path.
  443. transformed.path[ i ] -= howMany;
  444. }
  445. }
  446. }
  447. return transformed;
  448. }
  449. /**
  450. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  451. *
  452. * @protected
  453. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  454. * @param {Number} howMany How many nodes are inserted.
  455. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  456. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  457. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  458. * @returns {module:engine/model/position~Position} Transformed position.
  459. */
  460. _getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  461. let transformed = Position.createFromPosition( this );
  462. // This position can't be affected if insertion was in a different root.
  463. if ( this.root != insertPosition.root ) {
  464. return transformed;
  465. }
  466. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  467. // If nodes are inserted in the node that is pointed by this position...
  468. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  469. // And are inserted before an offset of that position...
  470. // "Push" this positions offset.
  471. transformed.offset += howMany;
  472. }
  473. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  474. // If nodes are inserted in a node that is on a path to this position...
  475. const i = insertPosition.path.length - 1;
  476. if ( insertPosition.offset <= this.path[ i ] ) {
  477. // And are inserted before next node of that path...
  478. // "Push" the index on that path.
  479. transformed.path[ i ] += howMany;
  480. }
  481. }
  482. return transformed;
  483. }
  484. /**
  485. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  486. *
  487. * @protected
  488. * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
  489. * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
  490. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  491. * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
  492. * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
  493. * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
  494. * @param {Boolean} [sticky] Flag indicating whether this position "sticks" to range, that is if it should be moved
  495. * with the moved range if it is equal to one of range's boundaries.
  496. * @returns {module:engine/model/position~Position} Transformed position.
  497. */
  498. _getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore, sticky ) {
  499. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  500. let transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  501. // Then we update target position, as it could be affected by nodes removal too.
  502. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  503. if ( transformed === null || ( sticky && transformed.isEqual( sourcePosition ) ) ) {
  504. // This position is inside moved range (or sticks to it).
  505. // In this case, we calculate a combination of this position, move source position and target position.
  506. transformed = this._getCombined( sourcePosition, targetPosition );
  507. } else {
  508. // This position is not inside a removed range.
  509. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  510. transformed = transformed._getTransformedByInsertion( targetPosition, howMany, insertBefore );
  511. }
  512. return transformed;
  513. }
  514. /**
  515. * Returns a new position that is a combination of this position and given positions.
  516. *
  517. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  518. * to the `target` position. It is expected that this position is inside the moved range.
  519. *
  520. * Example:
  521. *
  522. * let original = new Position( root, [ 2, 3, 1 ] );
  523. * let source = new Position( root, [ 2, 2 ] );
  524. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  525. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  526. *
  527. * Explanation:
  528. *
  529. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  530. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  531. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  532. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  533. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  534. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  535. *
  536. * @protected
  537. * @param {module:engine/model/position~Position} source Beginning of the moved range.
  538. * @param {module:engine/model/position~Position} target Position where the range is moved.
  539. * @returns {module:engine/model/position~Position} Combined position.
  540. */
  541. _getCombined( source, target ) {
  542. const i = source.path.length - 1;
  543. // The first part of a path to combined position is a path to the place where nodes were moved.
  544. let combined = Position.createFromPosition( target );
  545. // Then we have to update the rest of the path.
  546. // Fix the offset because this position might be after `from` position and we have to reflect that.
  547. combined.offset = combined.offset + this.path[ i ] - source.offset;
  548. // Then, add the rest of the path.
  549. // If this position is at the same level as `from` position nothing will get added.
  550. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  551. return combined;
  552. }
  553. /**
  554. * Creates position at the given location. The location can be specified as:
  555. *
  556. * * a {@link module:engine/model/position~Position position},
  557. * * parent element and offset (offset defaults to `0`),
  558. * * parent element and `'end'` (sets position at the end of that element),
  559. * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  560. *
  561. * This method is a shortcut to other constructors such as:
  562. *
  563. * * {@link module:engine/model/position~Position.createBefore},
  564. * * {@link module:engine/model/position~Position.createAfter},
  565. * * {@link module:engine/model/position~Position.createFromParentAndOffset},
  566. * * {@link module:engine/model/position~Position.createFromPosition}.
  567. *
  568. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  569. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  570. * first parameter is a {@link module:engine/model/item~Item model item}.
  571. */
  572. static createAt( itemOrPosition, offset ) {
  573. if ( itemOrPosition instanceof Position ) {
  574. return this.createFromPosition( itemOrPosition );
  575. } else {
  576. const node = itemOrPosition;
  577. if ( offset == 'end' ) {
  578. offset = node.maxOffset;
  579. } else if ( offset == 'before' ) {
  580. return this.createBefore( node );
  581. } else if ( offset == 'after' ) {
  582. return this.createAfter( node );
  583. } else if ( !offset ) {
  584. offset = 0;
  585. }
  586. return this.createFromParentAndOffset( node, offset );
  587. }
  588. }
  589. /**
  590. * Creates a new position, after given {@link module:engine/model/item~Item model item}.
  591. *
  592. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  593. * @returns {module:engine/model/position~Position}
  594. */
  595. static createAfter( item ) {
  596. if ( !item.parent ) {
  597. /**
  598. * You can not make position after root.
  599. *
  600. * @error position-after-root
  601. * @param {module:engine/model/item~Item} root
  602. */
  603. throw new CKEditorError( 'model-position-after-root: You can not make position after root.', { root: item } );
  604. }
  605. return this.createFromParentAndOffset( item.parent, item.endOffset );
  606. }
  607. /**
  608. * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
  609. *
  610. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  611. * @returns {module:engine/model/position~Position}
  612. */
  613. static createBefore( item ) {
  614. if ( !item.parent ) {
  615. /**
  616. * You can not make position before root.
  617. *
  618. * @error position-before-root
  619. * @param {module:engine/model/item~Item} root
  620. */
  621. throw new CKEditorError( 'model-position-before-root: You can not make position before root.', { root: item } );
  622. }
  623. return this.createFromParentAndOffset( item.parent, item.startOffset );
  624. }
  625. /**
  626. * Creates a new position from the parent element and an offset in that element.
  627. *
  628. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent Position's parent.
  629. * @param {Number} offset Position's offset.
  630. * @returns {module:engine/model/position~Position}
  631. */
  632. static createFromParentAndOffset( parent, offset ) {
  633. if ( !( parent instanceof Element || parent instanceof DocumentFragment ) ) {
  634. /**
  635. * Position parent have to be a model element or model document fragment.
  636. *
  637. * @error position-parent-incorrect
  638. */
  639. throw new CKEditorError( 'model-position-parent-incorrect: Position parent have to be a element or document fragment.' );
  640. }
  641. const path = parent.getPath();
  642. path.push( offset );
  643. return new this( parent.root, path );
  644. }
  645. /**
  646. * Creates a new position, which is equal to passed position.
  647. *
  648. * @param {module:engine/model/position~Position} position Position to be cloned.
  649. * @returns {module:engine/model/position~Position}
  650. */
  651. static createFromPosition( position ) {
  652. return new this( position.root, position.path.slice() );
  653. }
  654. /**
  655. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  656. *
  657. * @param {Object} json Plain object to be converted to `Position`.
  658. * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
  659. */
  660. static fromJSON( json, doc ) {
  661. if ( json.root === '$graveyard' ) {
  662. return new Position( doc.graveyard, json.path );
  663. }
  664. if ( !doc.hasRoot( json.root ) ) {
  665. /**
  666. * Cannot create position for document. Root with specified name does not exist.
  667. *
  668. * @error position-fromjson-no-root
  669. * @param {String} rootName
  670. */
  671. throw new CKEditorError(
  672. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  673. { rootName: json.root }
  674. );
  675. }
  676. return new Position( doc.getRoot( json.root ), json.path );
  677. }
  678. }
  679. /**
  680. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  681. * If positions are in different roots `'different'` flag is returned.
  682. *
  683. * @typedef {String} module:engine/model/position~PositionRelation
  684. */