position.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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 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 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: 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 it the tree. Path is described through 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. let 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( { includeNode: 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. let cmp = compareArrays( this.path, position.path );
  283. // If comparison returned string it means that arrays are same.
  284. let diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
  285. return this.path.slice( 0, diffAt );
  286. }
  287. /**
  288. * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
  289. * is shifted by `shift` value (can be a negative value).
  290. *
  291. * @param {Number} shift Offset shift. Can be a negative value.
  292. * @returns {module:engine/model/position~Position} Shifted position.
  293. */
  294. getShiftedBy( shift ) {
  295. let shifted = Position.createFromPosition( this );
  296. let offset = shifted.offset + shift;
  297. shifted.offset = offset < 0 ? 0 : offset;
  298. return shifted;
  299. }
  300. /**
  301. * Checks whether this position is after given position.
  302. *
  303. * @see module:engine/model/position~Position#isBefore
  304. *
  305. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  306. * @returns {Boolean} True if this position is after given position.
  307. */
  308. isAfter( otherPosition ) {
  309. return this.compareWith( otherPosition ) == 'after';
  310. }
  311. /**
  312. * Checks whether this position is before given position.
  313. *
  314. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  315. * be `true` if positions are in different roots and you might not expect this. You should probably use
  316. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  317. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  318. *
  319. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  320. * // do A.
  321. * } else {
  322. * // do B.
  323. * }
  324. *
  325. * or, if you have only one if-branch:
  326. *
  327. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  328. * // do B.
  329. * }
  330. *
  331. * rather than:
  332. *
  333. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  334. * // do B.
  335. * } else {
  336. * // do A.
  337. * }
  338. *
  339. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  340. * @returns {Boolean} True if this position is before given position.
  341. */
  342. isBefore( otherPosition ) {
  343. return this.compareWith( otherPosition ) == 'before';
  344. }
  345. /**
  346. * Checks whether this position is equal to given position.
  347. *
  348. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  349. * @returns {Boolean} True if positions are same.
  350. */
  351. isEqual( otherPosition ) {
  352. return this.compareWith( otherPosition ) == 'same';
  353. }
  354. /**
  355. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  356. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  357. * they are very similar or even indistinguishable.
  358. *
  359. * **Note:** this method traverses model document so it can be only used when range is up-to-date with model document.
  360. *
  361. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  362. * @returns {Boolean} True if positions touch.
  363. */
  364. isTouching( otherPosition ) {
  365. let left = null;
  366. let right = null;
  367. let compare = this.compareWith( otherPosition );
  368. switch ( compare ) {
  369. case 'same':
  370. return true;
  371. case 'before':
  372. left = Position.createFromPosition( this );
  373. right = Position.createFromPosition( otherPosition );
  374. break;
  375. case 'after':
  376. left = Position.createFromPosition( otherPosition );
  377. right = Position.createFromPosition( this );
  378. break;
  379. default:
  380. return false;
  381. }
  382. // Cached for optimization purposes.
  383. let leftParent = left.parent;
  384. while ( left.path.length + right.path.length ) {
  385. if ( left.isEqual( right ) ) {
  386. return true;
  387. }
  388. if ( left.path.length > right.path.length ) {
  389. if ( left.offset !== leftParent.maxOffset ) {
  390. return false;
  391. }
  392. left.path = left.path.slice( 0, -1 );
  393. leftParent = leftParent.parent;
  394. left.offset++;
  395. } else {
  396. if ( right.offset !== 0 ) {
  397. return false;
  398. }
  399. right.path = right.path.slice( 0, -1 );
  400. }
  401. }
  402. }
  403. /**
  404. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  405. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  406. *
  407. * @protected
  408. * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
  409. * @param {Number} howMany How many nodes are removed.
  410. * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
  411. */
  412. _getTransformedByDeletion( deletePosition, howMany ) {
  413. let transformed = Position.createFromPosition( this );
  414. // This position can't be affected if deletion was in a different root.
  415. if ( this.root != deletePosition.root ) {
  416. return transformed;
  417. }
  418. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  419. // If nodes are removed from the node that is pointed by this position...
  420. if ( deletePosition.offset < this.offset ) {
  421. // And are removed from before an offset of that position...
  422. if ( deletePosition.offset + howMany > this.offset ) {
  423. // Position is in removed range, it's no longer in the tree.
  424. return null;
  425. } else {
  426. // Decrement the offset accordingly.
  427. transformed.offset -= howMany;
  428. }
  429. }
  430. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  431. // If nodes are removed from a node that is on a path to this position...
  432. const i = deletePosition.path.length - 1;
  433. if ( deletePosition.offset <= this.path[ i ] ) {
  434. // And are removed from before next node of that path...
  435. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  436. // If the next node of that path is removed return null
  437. // because the node containing this position got removed.
  438. return null;
  439. } else {
  440. // Otherwise, decrement index on that path.
  441. transformed.path[ i ] -= howMany;
  442. }
  443. }
  444. }
  445. return transformed;
  446. }
  447. /**
  448. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  449. *
  450. * @protected
  451. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  452. * @param {Number} howMany How many nodes are inserted.
  453. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  454. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  455. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  456. * @returns {module:engine/model/position~Position} Transformed position.
  457. */
  458. _getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  459. let transformed = Position.createFromPosition( this );
  460. // This position can't be affected if insertion was in a different root.
  461. if ( this.root != insertPosition.root ) {
  462. return transformed;
  463. }
  464. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  465. // If nodes are inserted in the node that is pointed by this position...
  466. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  467. // And are inserted before an offset of that position...
  468. // "Push" this positions offset.
  469. transformed.offset += howMany;
  470. }
  471. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  472. // If nodes are inserted in a node that is on a path to this position...
  473. const i = insertPosition.path.length - 1;
  474. if ( insertPosition.offset <= this.path[ i ] ) {
  475. // And are inserted before next node of that path...
  476. // "Push" the index on that path.
  477. transformed.path[ i ] += howMany;
  478. }
  479. }
  480. return transformed;
  481. }
  482. /**
  483. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  484. *
  485. * @protected
  486. * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
  487. * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
  488. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  489. * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
  490. * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
  491. * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
  492. * @param {Boolean} [sticky] Flag indicating whether this position "sticks" to range, that is if it should be moved
  493. * with the moved range if it is equal to one of range's boundaries.
  494. * @returns {module:engine/model/position~Position} Transformed position.
  495. */
  496. _getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore, sticky ) {
  497. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  498. let transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  499. // Then we update target position, as it could be affected by nodes removal too.
  500. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  501. if ( transformed === null || ( sticky && transformed.isEqual( sourcePosition ) ) ) {
  502. // This position is inside moved range (or sticks to it).
  503. // In this case, we calculate a combination of this position, move source position and target position.
  504. transformed = this._getCombined( sourcePosition, targetPosition );
  505. } else {
  506. // This position is not inside a removed range.
  507. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  508. transformed = transformed._getTransformedByInsertion( targetPosition, howMany, insertBefore );
  509. }
  510. return transformed;
  511. }
  512. /**
  513. * Returns a new position that is a combination of this position and given positions.
  514. *
  515. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  516. * to the `target` position. It is expected that this position is inside the moved range.
  517. *
  518. * Example:
  519. *
  520. * let original = new Position( root, [ 2, 3, 1 ] );
  521. * let source = new Position( root, [ 2, 2 ] );
  522. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  523. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  524. *
  525. * Explanation:
  526. *
  527. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  528. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  529. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  530. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  531. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  532. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  533. *
  534. * @protected
  535. * @param {module:engine/model/position~Position} source Beginning of the moved range.
  536. * @param {module:engine/model/position~Position} target Position where the range is moved.
  537. * @returns {module:engine/model/position~Position} Combined position.
  538. */
  539. _getCombined( source, target ) {
  540. const i = source.path.length - 1;
  541. // The first part of a path to combined position is a path to the place where nodes were moved.
  542. let combined = Position.createFromPosition( target );
  543. // Then we have to update the rest of the path.
  544. // Fix the offset because this position might be after `from` position and we have to reflect that.
  545. combined.offset = combined.offset + this.path[ i ] - source.offset;
  546. // Then, add the rest of the path.
  547. // If this position is at the same level as `from` position nothing will get added.
  548. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  549. return combined;
  550. }
  551. /**
  552. * Creates position at the given location. The location can be specified as:
  553. *
  554. * * a {@link module:engine/model/position~Position position},
  555. * * parent element and offset (offset defaults to `0`),
  556. * * parent element and `'end'` (sets position at the end of that element),
  557. * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  558. *
  559. * This method is a shortcut to other constructors such as:
  560. *
  561. * * {@link module:engine/model/position~Position.createBefore},
  562. * * {@link module:engine/model/position~Position.createAfter},
  563. * * {@link module:engine/model/position~Position.createFromParentAndOffset},
  564. * * {@link module:engine/model/position~Position.createFromPosition}.
  565. *
  566. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  567. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  568. * first parameter is a {@link module:engine/model/item~Item model item}.
  569. */
  570. static createAt( itemOrPosition, offset ) {
  571. if ( itemOrPosition instanceof Position ) {
  572. return this.createFromPosition( itemOrPosition );
  573. } else {
  574. const node = itemOrPosition;
  575. if ( offset == 'end' ) {
  576. offset = node.maxOffset;
  577. } else if ( offset == 'before' ) {
  578. return this.createBefore( node );
  579. } else if ( offset == 'after' ) {
  580. return this.createAfter( node );
  581. } else if ( !offset ) {
  582. offset = 0;
  583. }
  584. return this.createFromParentAndOffset( node, offset );
  585. }
  586. }
  587. /**
  588. * Creates a new position, after given {@link module:engine/model/item~Item model item}.
  589. *
  590. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  591. * @returns {module:engine/model/position~Position}
  592. */
  593. static createAfter( item ) {
  594. if ( !item.parent ) {
  595. /**
  596. * You can not make position after root.
  597. *
  598. * @error position-after-root
  599. * @param {module:engine/model/item~Item} root
  600. */
  601. throw new CKEditorError( 'model-position-after-root: You can not make position after root.', { root: item } );
  602. }
  603. return this.createFromParentAndOffset( item.parent, item.endOffset );
  604. }
  605. /**
  606. * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
  607. *
  608. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  609. * @returns {module:engine/model/position~Position}
  610. */
  611. static createBefore( item ) {
  612. if ( !item.parent ) {
  613. /**
  614. * You can not make position before root.
  615. *
  616. * @error position-before-root
  617. * @param {module:engine/model/item~Item} root
  618. */
  619. throw new CKEditorError( 'model-position-before-root: You can not make position before root.', { root: item } );
  620. }
  621. return this.createFromParentAndOffset( item.parent, item.startOffset );
  622. }
  623. /**
  624. * Creates a new position from the parent element and an offset in that element.
  625. *
  626. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent Position's parent.
  627. * @param {Number} offset Position's offset.
  628. * @returns {module:engine/model/position~Position}
  629. */
  630. static createFromParentAndOffset( parent, offset ) {
  631. if ( !parent.is( 'element' ) && !parent.is( 'documentFragment' ) ) {
  632. /**
  633. * Position parent have to be a model element or model document fragment.
  634. *
  635. * @error position-parent-incorrect
  636. */
  637. throw new CKEditorError( 'model-position-parent-incorrect: Position parent have to be a element or document fragment.' );
  638. }
  639. const path = parent.getPath();
  640. path.push( offset );
  641. return new this( parent.root, path );
  642. }
  643. /**
  644. * Creates a new position, which is equal to passed position.
  645. *
  646. * @param {module:engine/model/position~Position} position Position to be cloned.
  647. * @returns {module:engine/model/position~Position}
  648. */
  649. static createFromPosition( position ) {
  650. return new this( position.root, position.path.slice() );
  651. }
  652. /**
  653. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  654. *
  655. * @param {Object} json Plain object to be converted to `Position`.
  656. * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
  657. */
  658. static fromJSON( json, doc ) {
  659. if ( json.root === '$graveyard' ) {
  660. return new Position( doc.graveyard, json.path );
  661. }
  662. if ( !doc.hasRoot( json.root ) ) {
  663. /**
  664. * Cannot create position for document. Root with specified name does not exist.
  665. *
  666. * @error position-fromjson-no-root
  667. * @param {String} rootName
  668. */
  669. throw new CKEditorError(
  670. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  671. { rootName: json.root }
  672. );
  673. }
  674. return new Position( doc.getRoot( json.root ), json.path );
  675. }
  676. }
  677. /**
  678. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  679. * If positions are in different roots `'different'` flag is returned.
  680. *
  681. * @typedef {String} module:engine/model/position~PositionRelation
  682. */