8
0

position.js 28 KB

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