position.js 28 KB

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