position.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/model/position
  7. */
  8. import TreeWalker from './treewalker';
  9. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import Text from './text';
  12. import { last } from 'lodash-es';
  13. // To check if component is loaded more than once.
  14. import '@ckeditor/ckeditor5-utils/src/version';
  15. /**
  16. * Represents a position in the model tree.
  17. *
  18. * A position is represented by its {@link module:engine/model/position~Position#root} and
  19. * a {@link module:engine/model/position~Position#path} in that root.
  20. *
  21. * You can create position instances via its constructor or the `createPosition*()` factory methods of
  22. * {@link module:engine/model/model~Model} and {@link module:engine/model/writer~Writer}.
  23. *
  24. * **Note:** Position is based on offsets, not indexes. This means that a position between two text nodes
  25. * `foo` and `bar` has offset `3`, not `1`. See {@link module:engine/model/position~Position#path} for more information.
  26. *
  27. * Since a position in the model is represented by a {@link module:engine/model/position~Position#root position root} and
  28. * {@link module:engine/model/position~Position#path position path} it is possible to create positions placed in non-existing places.
  29. * This requirement is important for operational transformation algorithms.
  30. *
  31. * Also, {@link module:engine/model/operation/operation~Operation operations}
  32. * kept in the {@link module:engine/model/document~Document#history document history}
  33. * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
  34. * after the document has changed.
  35. *
  36. * When changes are applied to the model, it may also happen that {@link module:engine/model/position~Position#parent position parent}
  37. * will change even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
  38. * {@link module:engine/model/position~Position#parent} and some other properties and methods will throw errors.
  39. *
  40. * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
  41. */
  42. export default class Position {
  43. /**
  44. * Creates a position.
  45. *
  46. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  47. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  48. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  49. * See {@link module:engine/model/position~PositionStickiness}.
  50. */
  51. constructor( root, path, stickiness = 'toNone' ) {
  52. if ( !root.is( 'element' ) && !root.is( 'documentFragment' ) ) {
  53. /**
  54. * Position root is invalid.
  55. *
  56. * Positions can only be anchored in elements or document fragments.
  57. *
  58. * @error model-position-root-invalid
  59. */
  60. throw new CKEditorError(
  61. 'model-position-root-invalid: Position root invalid.',
  62. root
  63. );
  64. }
  65. if ( !( path instanceof Array ) || path.length === 0 ) {
  66. /**
  67. * Position path must be an array with at least one item.
  68. *
  69. * @error model-position-path-incorrect
  70. * @param path
  71. */
  72. throw new CKEditorError(
  73. 'model-position-path-incorrect: Position path must be an array with at least one item.',
  74. root,
  75. { path }
  76. );
  77. }
  78. // Normalize the root and path (if element was passed).
  79. path = root.getPath().concat( path );
  80. root = root.root;
  81. /**
  82. * Root of the position path.
  83. *
  84. * @readonly
  85. * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
  86. * module:engine/model/position~Position#root
  87. */
  88. this.root = root;
  89. /**
  90. * Position of the node in the tree. **Path contains offsets, not indexes.**
  91. *
  92. * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
  93. * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
  94. * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
  95. * down to the position offset in it's parent.
  96. *
  97. * ROOT
  98. * |- P before: [ 0 ] after: [ 1 ]
  99. * |- UL before: [ 1 ] after: [ 2 ]
  100. * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
  101. * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
  102. * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
  103. * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
  104. *
  105. * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
  106. * greater than `1` you can place position offset between their start and end:
  107. *
  108. * ROOT
  109. * |- P
  110. * |- UL
  111. * |- LI
  112. * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
  113. * |- LI
  114. * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
  115. *
  116. * @readonly
  117. * @member {Array.<Number>} module:engine/model/position~Position#path
  118. */
  119. this.path = path;
  120. /**
  121. * Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
  122. *
  123. * @member {module:engine/model/position~PositionStickiness} module:engine/model/position~Position#stickiness
  124. */
  125. this.stickiness = stickiness;
  126. }
  127. /**
  128. * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
  129. * to the last item in position {@link module:engine/model/position~Position#path path}.
  130. *
  131. * @type {Number}
  132. */
  133. get offset() {
  134. return last( this.path );
  135. }
  136. /**
  137. * @param {Number} newOffset
  138. */
  139. set offset( newOffset ) {
  140. this.path[ this.path.length - 1 ] = newOffset;
  141. }
  142. /**
  143. * Parent element of this position.
  144. *
  145. * Keep in mind that `parent` value is calculated when the property is accessed.
  146. * If {@link module:engine/model/position~Position#path position path}
  147. * leads to a non-existing element, `parent` property will throw error.
  148. *
  149. * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
  150. *
  151. * @readonly
  152. * @type {module:engine/model/element~Element}
  153. */
  154. get parent() {
  155. let parent = this.root;
  156. for ( let i = 0; i < this.path.length - 1; i++ ) {
  157. parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
  158. }
  159. return parent;
  160. }
  161. /**
  162. * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
  163. * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
  164. * in text node, position index is equal to the index of that text node.
  165. *
  166. * @readonly
  167. * @type {Number}
  168. */
  169. get index() {
  170. return this.parent.offsetToIndex( this.offset );
  171. }
  172. /**
  173. * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
  174. * position is not in a text node.
  175. *
  176. * @readonly
  177. * @type {module:engine/model/text~Text|null}
  178. */
  179. get textNode() {
  180. const node = this.parent.getChild( this.index );
  181. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  182. }
  183. /**
  184. * Node directly after this position or `null` if this position is in text node.
  185. *
  186. * @readonly
  187. * @type {module:engine/model/node~Node|null}
  188. */
  189. get nodeAfter() {
  190. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  191. }
  192. /**
  193. * Node directly before this position or `null` if this position is in text node.
  194. *
  195. * @readonly
  196. * @type {Node}
  197. */
  198. get nodeBefore() {
  199. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  200. }
  201. /**
  202. * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  203. *
  204. * @readonly
  205. * @type {Boolean}
  206. */
  207. get isAtStart() {
  208. return this.offset === 0;
  209. }
  210. /**
  211. * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  212. *
  213. * @readonly
  214. * @type {Boolean}
  215. */
  216. get isAtEnd() {
  217. return this.offset == this.parent.maxOffset;
  218. }
  219. /**
  220. * Checks whether this position is before or after given position.
  221. *
  222. * This method is safe to use it on non-existing positions (for example during operational transformation).
  223. *
  224. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  225. * @returns {module:engine/model/position~PositionRelation}
  226. */
  227. compareWith( otherPosition ) {
  228. if ( this.root != otherPosition.root ) {
  229. return 'different';
  230. }
  231. const result = compareArrays( this.path, otherPosition.path );
  232. switch ( result ) {
  233. case 'same':
  234. return 'same';
  235. case 'prefix':
  236. return 'before';
  237. case 'extension':
  238. return 'after';
  239. default:
  240. return this.path[ result ] < otherPosition.path[ result ] ? 'before' : 'after';
  241. }
  242. }
  243. /**
  244. * Gets the farthest position which matches the callback using
  245. * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
  246. *
  247. * For example:
  248. *
  249. * getLastMatchingPosition( value => value.type == 'text' );
  250. * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
  251. *
  252. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
  253. * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
  254. *
  255. * getLastMatchingPosition( value => false );
  256. * // Do not move the position.
  257. *
  258. * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
  259. * return `true` if the value should be skipped or `false` if not.
  260. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  261. *
  262. * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
  263. */
  264. getLastMatchingPosition( skip, options = {} ) {
  265. options.startPosition = this;
  266. const treeWalker = new TreeWalker( options );
  267. treeWalker.skip( skip );
  268. return treeWalker.position;
  269. }
  270. /**
  271. * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
  272. * but without the last item.
  273. *
  274. * This method is safe to use it on non-existing positions (for example during operational transformation).
  275. *
  276. * @returns {Array.<Number>} Path to the parent.
  277. */
  278. getParentPath() {
  279. return this.path.slice( 0, -1 );
  280. }
  281. /**
  282. * Returns ancestors array of this position, that is this position's parent and its ancestors.
  283. *
  284. * @returns {Array.<module:engine/model/item~Item>} Array with ancestors.
  285. */
  286. getAncestors() {
  287. if ( this.parent.is( 'documentFragment' ) ) {
  288. return [ this.parent ];
  289. } else {
  290. return this.parent.getAncestors( { includeSelf: true } );
  291. }
  292. }
  293. /**
  294. * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
  295. * of these two paths must be identical.
  296. *
  297. * This method is safe to use it on non-existing positions (for example during operational transformation).
  298. *
  299. * @param {module:engine/model/position~Position} position The second position.
  300. * @returns {Array.<Number>} The common path.
  301. */
  302. getCommonPath( position ) {
  303. if ( this.root != position.root ) {
  304. return [];
  305. }
  306. // We find on which tree-level start and end have the lowest common ancestor
  307. const cmp = compareArrays( this.path, position.path );
  308. // If comparison returned string it means that arrays are same.
  309. const diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
  310. return this.path.slice( 0, diffAt );
  311. }
  312. /**
  313. * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  314. * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
  315. *
  316. * @param {module:engine/model/position~Position} position The second position.
  317. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  318. */
  319. getCommonAncestor( position ) {
  320. const ancestorsA = this.getAncestors();
  321. const ancestorsB = position.getAncestors();
  322. let i = 0;
  323. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  324. i++;
  325. }
  326. return i === 0 ? null : ancestorsA[ i - 1 ];
  327. }
  328. /**
  329. * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
  330. * is shifted by `shift` value (can be a negative value).
  331. *
  332. * This method is safe to use it on non-existing positions (for example during operational transformation).
  333. *
  334. * @param {Number} shift Offset shift. Can be a negative value.
  335. * @returns {module:engine/model/position~Position} Shifted position.
  336. */
  337. getShiftedBy( shift ) {
  338. const shifted = this.clone();
  339. const offset = shifted.offset + shift;
  340. shifted.offset = offset < 0 ? 0 : offset;
  341. return shifted;
  342. }
  343. /**
  344. * Checks whether this position is after given position.
  345. *
  346. * This method is safe to use it on non-existing positions (for example during operational transformation).
  347. *
  348. * @see module:engine/model/position~Position#isBefore
  349. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  350. * @returns {Boolean} True if this position is after given position.
  351. */
  352. isAfter( otherPosition ) {
  353. return this.compareWith( otherPosition ) == 'after';
  354. }
  355. /**
  356. * Checks whether this position is before given position.
  357. *
  358. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  359. * be `true` if positions are in different roots and you might not expect this. You should probably use
  360. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  361. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  362. *
  363. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  364. * // do A.
  365. * } else {
  366. * // do B.
  367. * }
  368. *
  369. * or, if you have only one if-branch:
  370. *
  371. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  372. * // do B.
  373. * }
  374. *
  375. * rather than:
  376. *
  377. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  378. * // do B.
  379. * } else {
  380. * // do A.
  381. * }
  382. *
  383. * This method is safe to use it on non-existing positions (for example during operational transformation).
  384. *
  385. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  386. * @returns {Boolean} True if this position is before given position.
  387. */
  388. isBefore( otherPosition ) {
  389. return this.compareWith( otherPosition ) == 'before';
  390. }
  391. /**
  392. * Checks whether this position is equal to given position.
  393. *
  394. * This method is safe to use it on non-existing positions (for example during operational transformation).
  395. *
  396. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  397. * @returns {Boolean} True if positions are same.
  398. */
  399. isEqual( otherPosition ) {
  400. return this.compareWith( otherPosition ) == 'same';
  401. }
  402. /**
  403. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  404. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  405. * they are very similar or even indistinguishable.
  406. *
  407. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  408. * @returns {Boolean} True if positions touch.
  409. */
  410. isTouching( otherPosition ) {
  411. let left = null;
  412. let right = null;
  413. const compare = this.compareWith( otherPosition );
  414. switch ( compare ) {
  415. case 'same':
  416. return true;
  417. case 'before':
  418. left = Position._createAt( this );
  419. right = Position._createAt( otherPosition );
  420. break;
  421. case 'after':
  422. left = Position._createAt( otherPosition );
  423. right = Position._createAt( this );
  424. break;
  425. default:
  426. return false;
  427. }
  428. // Cached for optimization purposes.
  429. let leftParent = left.parent;
  430. while ( left.path.length + right.path.length ) {
  431. if ( left.isEqual( right ) ) {
  432. return true;
  433. }
  434. if ( left.path.length > right.path.length ) {
  435. if ( left.offset !== leftParent.maxOffset ) {
  436. return false;
  437. }
  438. left.path = left.path.slice( 0, -1 );
  439. leftParent = leftParent.parent;
  440. left.offset++;
  441. } else {
  442. if ( right.offset !== 0 ) {
  443. return false;
  444. }
  445. right.path = right.path.slice( 0, -1 );
  446. }
  447. }
  448. }
  449. /**
  450. * Checks whether given object is of `position` type.
  451. *
  452. * @param {String} type
  453. * @returns {Boolean}
  454. */
  455. is( type ) {
  456. return type == 'position' || type == 'model:position';
  457. }
  458. /**
  459. * Checks if two positions are in the same parent.
  460. *
  461. * This method is safe to use it on non-existing positions (for example during operational transformation).
  462. *
  463. * @param {module:engine/model/position~Position} position Position to compare with.
  464. * @returns {Boolean} `true` if positions have the same parent, `false` otherwise.
  465. */
  466. hasSameParentAs( position ) {
  467. if ( this.root !== position.root ) {
  468. return false;
  469. }
  470. const thisParentPath = this.getParentPath();
  471. const posParentPath = position.getParentPath();
  472. return compareArrays( thisParentPath, posParentPath ) == 'same';
  473. }
  474. /**
  475. * Returns a copy of this position that is transformed by given `operation`.
  476. *
  477. * The new position's parameters are updated accordingly to the effect of the `operation`.
  478. *
  479. * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
  480. * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
  481. *
  482. * This method is safe to use it on non-existing positions (for example during operational transformation).
  483. *
  484. * @param {module:engine/model/operation/operation~Operation} operation Operation to transform by.
  485. * @returns {module:engine/model/position~Position} Transformed position.
  486. */
  487. getTransformedByOperation( operation ) {
  488. let result;
  489. switch ( operation.type ) {
  490. case 'insert':
  491. result = this._getTransformedByInsertOperation( operation );
  492. break;
  493. case 'move':
  494. case 'remove':
  495. case 'reinsert':
  496. result = this._getTransformedByMoveOperation( operation );
  497. break;
  498. case 'split':
  499. result = this._getTransformedBySplitOperation( operation );
  500. break;
  501. case 'merge':
  502. result = this._getTransformedByMergeOperation( operation );
  503. break;
  504. default:
  505. result = Position._createAt( this );
  506. break;
  507. }
  508. return result;
  509. }
  510. /**
  511. * Returns a copy of this position transformed by an insert operation.
  512. *
  513. * @protected
  514. * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
  515. * @returns {module:engine/model/position~Position}
  516. */
  517. _getTransformedByInsertOperation( operation ) {
  518. return this._getTransformedByInsertion( operation.position, operation.howMany );
  519. }
  520. /**
  521. * Returns a copy of this position transformed by a move operation.
  522. *
  523. * @protected
  524. * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
  525. * @returns {module:engine/model/position~Position}
  526. */
  527. _getTransformedByMoveOperation( operation ) {
  528. return this._getTransformedByMove( operation.sourcePosition, operation.targetPosition, operation.howMany );
  529. }
  530. /**
  531. * Returns a copy of this position transformed by a split operation.
  532. *
  533. * @protected
  534. * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
  535. * @returns {module:engine/model/position~Position}
  536. */
  537. _getTransformedBySplitOperation( operation ) {
  538. const movedRange = operation.movedRange;
  539. const isContained = movedRange.containsPosition( this ) ||
  540. ( movedRange.start.isEqual( this ) && this.stickiness == 'toNext' );
  541. if ( isContained ) {
  542. return this._getCombined( operation.splitPosition, operation.moveTargetPosition );
  543. } else {
  544. if ( operation.graveyardPosition ) {
  545. return this._getTransformedByMove( operation.graveyardPosition, operation.insertionPosition, 1 );
  546. } else {
  547. return this._getTransformedByInsertion( operation.insertionPosition, 1 );
  548. }
  549. }
  550. }
  551. /**
  552. * Returns a copy of this position transformed by merge operation.
  553. *
  554. * @protected
  555. * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
  556. * @returns {module:engine/model/position~Position}
  557. */
  558. _getTransformedByMergeOperation( operation ) {
  559. const movedRange = operation.movedRange;
  560. const isContained = movedRange.containsPosition( this ) || movedRange.start.isEqual( this );
  561. let pos;
  562. if ( isContained ) {
  563. pos = this._getCombined( operation.sourcePosition, operation.targetPosition );
  564. if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
  565. // Above happens during OT when the merged element is moved before the merged-to element.
  566. pos = pos._getTransformedByDeletion( operation.deletionPosition, 1 );
  567. }
  568. } else if ( this.isEqual( operation.deletionPosition ) ) {
  569. pos = Position._createAt( operation.deletionPosition );
  570. } else {
  571. pos = this._getTransformedByMove( operation.deletionPosition, operation.graveyardPosition, 1 );
  572. }
  573. return pos;
  574. }
  575. /**
  576. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  577. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  578. *
  579. * @protected
  580. * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
  581. * @param {Number} howMany How many nodes are removed.
  582. * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
  583. */
  584. _getTransformedByDeletion( deletePosition, howMany ) {
  585. const transformed = Position._createAt( this );
  586. // This position can't be affected if deletion was in a different root.
  587. if ( this.root != deletePosition.root ) {
  588. return transformed;
  589. }
  590. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  591. // If nodes are removed from the node that is pointed by this position...
  592. if ( deletePosition.offset < this.offset ) {
  593. // And are removed from before an offset of that position...
  594. if ( deletePosition.offset + howMany > this.offset ) {
  595. // Position is in removed range, it's no longer in the tree.
  596. return null;
  597. } else {
  598. // Decrement the offset accordingly.
  599. transformed.offset -= howMany;
  600. }
  601. }
  602. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  603. // If nodes are removed from a node that is on a path to this position...
  604. const i = deletePosition.path.length - 1;
  605. if ( deletePosition.offset <= this.path[ i ] ) {
  606. // And are removed from before next node of that path...
  607. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  608. // If the next node of that path is removed return null
  609. // because the node containing this position got removed.
  610. return null;
  611. } else {
  612. // Otherwise, decrement index on that path.
  613. transformed.path[ i ] -= howMany;
  614. }
  615. }
  616. }
  617. return transformed;
  618. }
  619. /**
  620. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  621. *
  622. * @protected
  623. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  624. * @param {Number} howMany How many nodes are inserted.
  625. * @returns {module:engine/model/position~Position} Transformed position.
  626. */
  627. _getTransformedByInsertion( insertPosition, howMany ) {
  628. const transformed = Position._createAt( this );
  629. // This position can't be affected if insertion was in a different root.
  630. if ( this.root != insertPosition.root ) {
  631. return transformed;
  632. }
  633. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  634. // If nodes are inserted in the node that is pointed by this position...
  635. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && this.stickiness != 'toPrevious' ) ) {
  636. // And are inserted before an offset of that position...
  637. // "Push" this positions offset.
  638. transformed.offset += howMany;
  639. }
  640. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  641. // If nodes are inserted in a node that is on a path to this position...
  642. const i = insertPosition.path.length - 1;
  643. if ( insertPosition.offset <= this.path[ i ] ) {
  644. // And are inserted before next node of that path...
  645. // "Push" the index on that path.
  646. transformed.path[ i ] += howMany;
  647. }
  648. }
  649. return transformed;
  650. }
  651. /**
  652. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  653. *
  654. * @protected
  655. * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
  656. * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
  657. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  658. * @returns {module:engine/model/position~Position} Transformed position.
  659. */
  660. _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
  661. // Update target position, as it could be affected by nodes removal.
  662. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  663. if ( sourcePosition.isEqual( targetPosition ) ) {
  664. // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
  665. return Position._createAt( this );
  666. }
  667. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  668. const transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  669. const isMoved = transformed === null ||
  670. ( sourcePosition.isEqual( this ) && this.stickiness == 'toNext' ) ||
  671. ( sourcePosition.getShiftedBy( howMany ).isEqual( this ) && this.stickiness == 'toPrevious' );
  672. if ( isMoved ) {
  673. // This position is inside moved range (or sticks to it).
  674. // In this case, we calculate a combination of this position, move source position and target position.
  675. return this._getCombined( sourcePosition, targetPosition );
  676. } else {
  677. // This position is not inside a removed range.
  678. //
  679. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  680. return transformed._getTransformedByInsertion( targetPosition, howMany );
  681. }
  682. }
  683. /**
  684. * Returns a new position that is a combination of this position and given positions.
  685. *
  686. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  687. * to the `target` position. It is expected that this position is inside the moved range.
  688. *
  689. * Example:
  690. *
  691. * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
  692. * let source = model.createPositionFromPath( root, [ 2, 2 ] );
  693. * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
  694. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  695. *
  696. * Explanation:
  697. *
  698. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  699. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  700. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  701. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  702. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  703. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  704. *
  705. * @protected
  706. * @param {module:engine/model/position~Position} source Beginning of the moved range.
  707. * @param {module:engine/model/position~Position} target Position where the range is moved.
  708. * @returns {module:engine/model/position~Position} Combined position.
  709. */
  710. _getCombined( source, target ) {
  711. const i = source.path.length - 1;
  712. // The first part of a path to combined position is a path to the place where nodes were moved.
  713. const combined = Position._createAt( target );
  714. combined.stickiness = this.stickiness;
  715. // Then we have to update the rest of the path.
  716. // Fix the offset because this position might be after `from` position and we have to reflect that.
  717. combined.offset = combined.offset + this.path[ i ] - source.offset;
  718. // Then, add the rest of the path.
  719. // If this position is at the same level as `from` position nothing will get added.
  720. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  721. return combined;
  722. }
  723. /**
  724. * @inheritDoc
  725. */
  726. toJSON() {
  727. return {
  728. root: this.root.toJSON(),
  729. path: Array.from( this.path ),
  730. stickiness: this.stickiness
  731. };
  732. }
  733. /**
  734. * Returns a new position that is equal to current position.
  735. *
  736. * @returns {module:engine/model/position~Position}
  737. */
  738. clone() {
  739. return new this.constructor( this.root, this.path, this.stickiness );
  740. }
  741. /**
  742. * Creates position at the given location. The location can be specified as:
  743. *
  744. * * a {@link module:engine/model/position~Position position},
  745. * * parent element and offset (offset defaults to `0`),
  746. * * parent element and `'end'` (sets position at the end of that element),
  747. * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  748. *
  749. * This method is a shortcut to other factory methods such as:
  750. *
  751. * * {@link module:engine/model/position~Position._createBefore},
  752. * * {@link module:engine/model/position~Position._createAfter}.
  753. *
  754. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  755. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when the
  756. * first parameter is a {@link module:engine/model/item~Item model item}.
  757. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness. Used only when the
  758. * first parameter is a {@link module:engine/model/item~Item model item}.
  759. * @protected
  760. */
  761. static _createAt( itemOrPosition, offset, stickiness = 'toNone' ) {
  762. if ( itemOrPosition instanceof Position ) {
  763. return new Position( itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness );
  764. } else {
  765. const node = itemOrPosition;
  766. if ( offset == 'end' ) {
  767. offset = node.maxOffset;
  768. } else if ( offset == 'before' ) {
  769. return this._createBefore( node, stickiness );
  770. } else if ( offset == 'after' ) {
  771. return this._createAfter( node, stickiness );
  772. } else if ( offset !== 0 && !offset ) {
  773. /**
  774. * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
  775. * requires the offset to be specified when the first parameter is a model item.
  776. *
  777. * @error model-createPositionAt-offset-required
  778. */
  779. throw new CKEditorError(
  780. 'model-createPositionAt-offset-required: ' +
  781. 'Model#createPositionAt() requires the offset when the first parameter is a model item.',
  782. [ this, itemOrPosition ]
  783. );
  784. }
  785. if ( !node.is( 'element' ) && !node.is( 'documentFragment' ) ) {
  786. /**
  787. * Position parent have to be a model element or model document fragment.
  788. *
  789. * @error model-position-parent-incorrect
  790. */
  791. throw new CKEditorError(
  792. 'model-position-parent-incorrect: Position parent have to be a element or document fragment.',
  793. [ this, itemOrPosition ]
  794. );
  795. }
  796. const path = node.getPath();
  797. path.push( offset );
  798. return new this( node.root, path, stickiness );
  799. }
  800. }
  801. /**
  802. * Creates a new position, after given {@link module:engine/model/item~Item model item}.
  803. *
  804. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  805. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  806. * @returns {module:engine/model/position~Position}
  807. * @protected
  808. */
  809. static _createAfter( item, stickiness ) {
  810. if ( !item.parent ) {
  811. /**
  812. * You can not make a position after a root element.
  813. *
  814. * @error model-position-after-root
  815. * @param {module:engine/model/item~Item} root
  816. */
  817. throw new CKEditorError(
  818. 'model-position-after-root: You cannot make a position after root.',
  819. [ this, item ],
  820. { root: item }
  821. );
  822. }
  823. return this._createAt( item.parent, item.endOffset, stickiness );
  824. }
  825. /**
  826. * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
  827. *
  828. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  829. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  830. * @returns {module:engine/model/position~Position}
  831. * @protected
  832. */
  833. static _createBefore( item, stickiness ) {
  834. if ( !item.parent ) {
  835. /**
  836. * You can not make a position before a root element.
  837. *
  838. * @error model-position-before-root
  839. * @param {module:engine/model/item~Item} root
  840. */
  841. throw new CKEditorError(
  842. 'model-position-before-root: You cannot make a position before root.',
  843. item,
  844. { root: item }
  845. );
  846. }
  847. return this._createAt( item.parent, item.startOffset, stickiness );
  848. }
  849. /**
  850. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  851. *
  852. * @param {Object} json Plain object to be converted to `Position`.
  853. * @param {module:engine/model/document~Document} doc Document object that will be position owner.
  854. * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
  855. */
  856. static fromJSON( json, doc ) {
  857. if ( json.root === '$graveyard' ) {
  858. const pos = new Position( doc.graveyard, json.path );
  859. pos.stickiness = json.stickiness;
  860. return pos;
  861. }
  862. if ( !doc.getRoot( json.root ) ) {
  863. /**
  864. * Cannot create position for document. Root with specified name does not exist.
  865. *
  866. * @error model-position-fromjson-no-root
  867. * @param {String} rootName
  868. */
  869. throw new CKEditorError(
  870. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  871. doc,
  872. { rootName: json.root }
  873. );
  874. }
  875. return new Position( doc.getRoot( json.root ), json.path, json.stickiness );
  876. }
  877. }
  878. /**
  879. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  880. * If positions are in different roots `'different'` flag is returned.
  881. *
  882. * @typedef {String} module:engine/model/position~PositionRelation
  883. */
  884. /**
  885. * Represents how position is "sticking" with neighbour nodes. Used to define how position should be transformed (moved)
  886. * in edge cases. Possible values: `'toNone'`, `'toNext'`, `'toPrevious'`.
  887. *
  888. * Examples:
  889. *
  890. * Insert. Position is at | and nodes are inserted at the same position, marked as ^:
  891. *
  892. * - sticks to none: <p>f^|oo</p> -> <p>fbar|oo</p>
  893. * - sticks to next node: <p>f^|oo</p> -> <p>fbar|oo</p>
  894. * - sticks to previous node: <p>f|^oo</p> -> <p>f|baroo</p>
  895. *
  896. *
  897. * Move. Position is at | and range [oo] is moved to position ^:
  898. *
  899. * - sticks to none: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  900. * - sticks to none: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  901. *
  902. * - sticks to next node: <p>f|[oo]</p><p>b^ar</p> -> <p>f</p><p>b|ooar</p>
  903. * - sticks to next node: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  904. *
  905. * - sticks to previous node: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  906. * - sticks to previous node: <p>f[oo]|</p><p>b^ar</p> -> <p>f</p><p>boo|ar</p>
  907. *
  908. * @typedef {String} module:engine/model/position~PositionStickiness
  909. */