position.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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-format
  70. * @param path
  71. */
  72. throw new CKEditorError(
  73. 'model-position-path-incorrect-format: 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|module:engine/model/documentfragment~DocumentFragment}
  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. if ( !parent ) {
  159. throw new CKEditorError( 'model-position-path-incorrect: The position\'s path is incorrect.', this, { position: this } );
  160. }
  161. }
  162. if ( parent.is( 'text' ) ) {
  163. /**
  164. * The position's path is incorrect. This means that a position does not point to
  165. * a correct place in the tree and hence, some of its methods and getters cannot work correctly.
  166. *
  167. * **Note**: Unlike DOM and view positions, in the model, the
  168. * {@link module:engine/model/position~Position#parent position's parent} is always an element or a document fragment.
  169. * The last offset in the {@link module:engine/model/position~Position#path position's path} is the point in this element where
  170. * this position points.
  171. *
  172. * Read more about model positions and offsets in
  173. * the {@glink framework/guides/architecture/editing-engine#indexes-and-offsets Editing engine architecture guide}.
  174. *
  175. * @error position-incorrect-path
  176. * @param {module:engine/model/position~Position} position The incorrect position.
  177. */
  178. throw new CKEditorError( 'model-position-path-incorrect: The position\'s path is incorrect.', this, { position: this } );
  179. }
  180. return parent;
  181. }
  182. /**
  183. * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
  184. * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
  185. * in text node, position index is equal to the index of that text node.
  186. *
  187. * @readonly
  188. * @type {Number}
  189. */
  190. get index() {
  191. return this.parent.offsetToIndex( this.offset );
  192. }
  193. /**
  194. * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
  195. * position is not in a text node.
  196. *
  197. * @readonly
  198. * @type {module:engine/model/text~Text|null}
  199. */
  200. get textNode() {
  201. const node = this.parent.getChild( this.index );
  202. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  203. }
  204. /**
  205. * Node directly after this position or `null` if this position is in text node.
  206. *
  207. * @readonly
  208. * @type {module:engine/model/node~Node|null}
  209. */
  210. get nodeAfter() {
  211. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  212. }
  213. /**
  214. * Node directly before this position or `null` if this position is in text node.
  215. *
  216. * @readonly
  217. * @type {Node}
  218. */
  219. get nodeBefore() {
  220. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  221. }
  222. /**
  223. * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  224. *
  225. * @readonly
  226. * @type {Boolean}
  227. */
  228. get isAtStart() {
  229. return this.offset === 0;
  230. }
  231. /**
  232. * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
  233. *
  234. * @readonly
  235. * @type {Boolean}
  236. */
  237. get isAtEnd() {
  238. return this.offset == this.parent.maxOffset;
  239. }
  240. /**
  241. * Checks whether this position is before or after given position.
  242. *
  243. * This method is safe to use it on non-existing positions (for example during operational transformation).
  244. *
  245. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  246. * @returns {module:engine/model/position~PositionRelation}
  247. */
  248. compareWith( otherPosition ) {
  249. if ( this.root != otherPosition.root ) {
  250. return 'different';
  251. }
  252. const result = compareArrays( this.path, otherPosition.path );
  253. switch ( result ) {
  254. case 'same':
  255. return 'same';
  256. case 'prefix':
  257. return 'before';
  258. case 'extension':
  259. return 'after';
  260. default:
  261. return this.path[ result ] < otherPosition.path[ result ] ? 'before' : 'after';
  262. }
  263. }
  264. /**
  265. * Gets the farthest position which matches the callback using
  266. * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
  267. *
  268. * For example:
  269. *
  270. * getLastMatchingPosition( value => value.type == 'text' );
  271. * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
  272. *
  273. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
  274. * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
  275. *
  276. * getLastMatchingPosition( value => false );
  277. * // Do not move the position.
  278. *
  279. * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
  280. * return `true` if the value should be skipped or `false` if not.
  281. * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
  282. *
  283. * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
  284. */
  285. getLastMatchingPosition( skip, options = {} ) {
  286. options.startPosition = this;
  287. const treeWalker = new TreeWalker( options );
  288. treeWalker.skip( skip );
  289. return treeWalker.position;
  290. }
  291. /**
  292. * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
  293. * but without the last item.
  294. *
  295. * This method is safe to use it on non-existing positions (for example during operational transformation).
  296. *
  297. * @returns {Array.<Number>} Path to the parent.
  298. */
  299. getParentPath() {
  300. return this.path.slice( 0, -1 );
  301. }
  302. /**
  303. * Returns ancestors array of this position, that is this position's parent and its ancestors.
  304. *
  305. * @returns {Array.<module:engine/model/item~Item>} Array with ancestors.
  306. */
  307. getAncestors() {
  308. if ( this.parent.is( 'documentFragment' ) ) {
  309. return [ this.parent ];
  310. } else {
  311. return this.parent.getAncestors( { includeSelf: true } );
  312. }
  313. }
  314. /**
  315. * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
  316. * of these two paths must be identical.
  317. *
  318. * This method is safe to use it on non-existing positions (for example during operational transformation).
  319. *
  320. * @param {module:engine/model/position~Position} position The second position.
  321. * @returns {Array.<Number>} The common path.
  322. */
  323. getCommonPath( position ) {
  324. if ( this.root != position.root ) {
  325. return [];
  326. }
  327. // We find on which tree-level start and end have the lowest common ancestor
  328. const cmp = compareArrays( this.path, position.path );
  329. // If comparison returned string it means that arrays are same.
  330. const diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
  331. return this.path.slice( 0, diffAt );
  332. }
  333. /**
  334. * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  335. * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
  336. *
  337. * @param {module:engine/model/position~Position} position The second position.
  338. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  339. */
  340. getCommonAncestor( position ) {
  341. const ancestorsA = this.getAncestors();
  342. const ancestorsB = position.getAncestors();
  343. let i = 0;
  344. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  345. i++;
  346. }
  347. return i === 0 ? null : ancestorsA[ i - 1 ];
  348. }
  349. /**
  350. * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
  351. * is shifted by `shift` value (can be a negative value).
  352. *
  353. * This method is safe to use it on non-existing positions (for example during operational transformation).
  354. *
  355. * @param {Number} shift Offset shift. Can be a negative value.
  356. * @returns {module:engine/model/position~Position} Shifted position.
  357. */
  358. getShiftedBy( shift ) {
  359. const shifted = this.clone();
  360. const offset = shifted.offset + shift;
  361. shifted.offset = offset < 0 ? 0 : offset;
  362. return shifted;
  363. }
  364. /**
  365. * Checks whether this position is after given position.
  366. *
  367. * This method is safe to use it on non-existing positions (for example during operational transformation).
  368. *
  369. * @see module:engine/model/position~Position#isBefore
  370. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  371. * @returns {Boolean} True if this position is after given position.
  372. */
  373. isAfter( otherPosition ) {
  374. return this.compareWith( otherPosition ) == 'after';
  375. }
  376. /**
  377. * Checks whether this position is before given position.
  378. *
  379. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  380. * be `true` if positions are in different roots and you might not expect this. You should probably use
  381. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  382. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  383. *
  384. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  385. * // do A.
  386. * } else {
  387. * // do B.
  388. * }
  389. *
  390. * or, if you have only one if-branch:
  391. *
  392. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  393. * // do B.
  394. * }
  395. *
  396. * rather than:
  397. *
  398. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  399. * // do B.
  400. * } else {
  401. * // do A.
  402. * }
  403. *
  404. * This method is safe to use it on non-existing positions (for example during operational transformation).
  405. *
  406. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  407. * @returns {Boolean} True if this position is before given position.
  408. */
  409. isBefore( otherPosition ) {
  410. return this.compareWith( otherPosition ) == 'before';
  411. }
  412. /**
  413. * Checks whether this position is equal to given position.
  414. *
  415. * This method is safe to use it on non-existing positions (for example during operational transformation).
  416. *
  417. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  418. * @returns {Boolean} True if positions are same.
  419. */
  420. isEqual( otherPosition ) {
  421. return this.compareWith( otherPosition ) == 'same';
  422. }
  423. /**
  424. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  425. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  426. * they are very similar or even indistinguishable.
  427. *
  428. * @param {module:engine/model/position~Position} otherPosition Position to compare with.
  429. * @returns {Boolean} True if positions touch.
  430. */
  431. isTouching( otherPosition ) {
  432. let left = null;
  433. let right = null;
  434. const compare = this.compareWith( otherPosition );
  435. switch ( compare ) {
  436. case 'same':
  437. return true;
  438. case 'before':
  439. left = Position._createAt( this );
  440. right = Position._createAt( otherPosition );
  441. break;
  442. case 'after':
  443. left = Position._createAt( otherPosition );
  444. right = Position._createAt( this );
  445. break;
  446. default:
  447. return false;
  448. }
  449. // Cached for optimization purposes.
  450. let leftParent = left.parent;
  451. while ( left.path.length + right.path.length ) {
  452. if ( left.isEqual( right ) ) {
  453. return true;
  454. }
  455. if ( left.path.length > right.path.length ) {
  456. if ( left.offset !== leftParent.maxOffset ) {
  457. return false;
  458. }
  459. left.path = left.path.slice( 0, -1 );
  460. leftParent = leftParent.parent;
  461. left.offset++;
  462. } else {
  463. if ( right.offset !== 0 ) {
  464. return false;
  465. }
  466. right.path = right.path.slice( 0, -1 );
  467. }
  468. }
  469. }
  470. /**
  471. * Checks whether this object is of the given.
  472. *
  473. * position.is( 'position' ); // -> true
  474. * position.is( 'model:position' ); // -> true
  475. *
  476. * position.is( 'view:position' ); // -> false
  477. * position.is( 'documentSelection' ); // -> false
  478. *
  479. * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
  480. *
  481. * @param {String} type
  482. * @returns {Boolean}
  483. */
  484. is( type ) {
  485. return type == 'position' || type == 'model:position';
  486. }
  487. /**
  488. * Checks if two positions are in the same parent.
  489. *
  490. * This method is safe to use it on non-existing positions (for example during operational transformation).
  491. *
  492. * @param {module:engine/model/position~Position} position Position to compare with.
  493. * @returns {Boolean} `true` if positions have the same parent, `false` otherwise.
  494. */
  495. hasSameParentAs( position ) {
  496. if ( this.root !== position.root ) {
  497. return false;
  498. }
  499. const thisParentPath = this.getParentPath();
  500. const posParentPath = position.getParentPath();
  501. return compareArrays( thisParentPath, posParentPath ) == 'same';
  502. }
  503. /**
  504. * Returns a copy of this position that is transformed by given `operation`.
  505. *
  506. * The new position's parameters are updated accordingly to the effect of the `operation`.
  507. *
  508. * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
  509. * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
  510. *
  511. * This method is safe to use it on non-existing positions (for example during operational transformation).
  512. *
  513. * @param {module:engine/model/operation/operation~Operation} operation Operation to transform by.
  514. * @returns {module:engine/model/position~Position} Transformed position.
  515. */
  516. getTransformedByOperation( operation ) {
  517. let result;
  518. switch ( operation.type ) {
  519. case 'insert':
  520. result = this._getTransformedByInsertOperation( operation );
  521. break;
  522. case 'move':
  523. case 'remove':
  524. case 'reinsert':
  525. result = this._getTransformedByMoveOperation( operation );
  526. break;
  527. case 'split':
  528. result = this._getTransformedBySplitOperation( operation );
  529. break;
  530. case 'merge':
  531. result = this._getTransformedByMergeOperation( operation );
  532. break;
  533. default:
  534. result = Position._createAt( this );
  535. break;
  536. }
  537. return result;
  538. }
  539. /**
  540. * Returns a copy of this position transformed by an insert operation.
  541. *
  542. * @protected
  543. * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
  544. * @returns {module:engine/model/position~Position}
  545. */
  546. _getTransformedByInsertOperation( operation ) {
  547. return this._getTransformedByInsertion( operation.position, operation.howMany );
  548. }
  549. /**
  550. * Returns a copy of this position transformed by a move operation.
  551. *
  552. * @protected
  553. * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
  554. * @returns {module:engine/model/position~Position}
  555. */
  556. _getTransformedByMoveOperation( operation ) {
  557. return this._getTransformedByMove( operation.sourcePosition, operation.targetPosition, operation.howMany );
  558. }
  559. /**
  560. * Returns a copy of this position transformed by a split operation.
  561. *
  562. * @protected
  563. * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
  564. * @returns {module:engine/model/position~Position}
  565. */
  566. _getTransformedBySplitOperation( operation ) {
  567. const movedRange = operation.movedRange;
  568. const isContained = movedRange.containsPosition( this ) ||
  569. ( movedRange.start.isEqual( this ) && this.stickiness == 'toNext' );
  570. if ( isContained ) {
  571. return this._getCombined( operation.splitPosition, operation.moveTargetPosition );
  572. } else {
  573. if ( operation.graveyardPosition ) {
  574. return this._getTransformedByMove( operation.graveyardPosition, operation.insertionPosition, 1 );
  575. } else {
  576. return this._getTransformedByInsertion( operation.insertionPosition, 1 );
  577. }
  578. }
  579. }
  580. /**
  581. * Returns a copy of this position transformed by merge operation.
  582. *
  583. * @protected
  584. * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
  585. * @returns {module:engine/model/position~Position}
  586. */
  587. _getTransformedByMergeOperation( operation ) {
  588. const movedRange = operation.movedRange;
  589. const isContained = movedRange.containsPosition( this ) || movedRange.start.isEqual( this );
  590. let pos;
  591. if ( isContained ) {
  592. pos = this._getCombined( operation.sourcePosition, operation.targetPosition );
  593. if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
  594. // Above happens during OT when the merged element is moved before the merged-to element.
  595. pos = pos._getTransformedByDeletion( operation.deletionPosition, 1 );
  596. }
  597. } else if ( this.isEqual( operation.deletionPosition ) ) {
  598. pos = Position._createAt( operation.deletionPosition );
  599. } else {
  600. pos = this._getTransformedByMove( operation.deletionPosition, operation.graveyardPosition, 1 );
  601. }
  602. return pos;
  603. }
  604. /**
  605. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  606. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  607. *
  608. * @protected
  609. * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
  610. * @param {Number} howMany How many nodes are removed.
  611. * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
  612. */
  613. _getTransformedByDeletion( deletePosition, howMany ) {
  614. const transformed = Position._createAt( this );
  615. // This position can't be affected if deletion was in a different root.
  616. if ( this.root != deletePosition.root ) {
  617. return transformed;
  618. }
  619. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  620. // If nodes are removed from the node that is pointed by this position...
  621. if ( deletePosition.offset < this.offset ) {
  622. // And are removed from before an offset of that position...
  623. if ( deletePosition.offset + howMany > this.offset ) {
  624. // Position is in removed range, it's no longer in the tree.
  625. return null;
  626. } else {
  627. // Decrement the offset accordingly.
  628. transformed.offset -= howMany;
  629. }
  630. }
  631. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  632. // If nodes are removed from a node that is on a path to this position...
  633. const i = deletePosition.path.length - 1;
  634. if ( deletePosition.offset <= this.path[ i ] ) {
  635. // And are removed from before next node of that path...
  636. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  637. // If the next node of that path is removed return null
  638. // because the node containing this position got removed.
  639. return null;
  640. } else {
  641. // Otherwise, decrement index on that path.
  642. transformed.path[ i ] -= howMany;
  643. }
  644. }
  645. }
  646. return transformed;
  647. }
  648. /**
  649. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  650. *
  651. * @protected
  652. * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
  653. * @param {Number} howMany How many nodes are inserted.
  654. * @returns {module:engine/model/position~Position} Transformed position.
  655. */
  656. _getTransformedByInsertion( insertPosition, howMany ) {
  657. const transformed = Position._createAt( this );
  658. // This position can't be affected if insertion was in a different root.
  659. if ( this.root != insertPosition.root ) {
  660. return transformed;
  661. }
  662. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  663. // If nodes are inserted in the node that is pointed by this position...
  664. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && this.stickiness != 'toPrevious' ) ) {
  665. // And are inserted before an offset of that position...
  666. // "Push" this positions offset.
  667. transformed.offset += howMany;
  668. }
  669. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  670. // If nodes are inserted in a node that is on a path to this position...
  671. const i = insertPosition.path.length - 1;
  672. if ( insertPosition.offset <= this.path[ i ] ) {
  673. // And are inserted before next node of that path...
  674. // "Push" the index on that path.
  675. transformed.path[ i ] += howMany;
  676. }
  677. }
  678. return transformed;
  679. }
  680. /**
  681. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  682. *
  683. * @protected
  684. * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
  685. * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
  686. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  687. * @returns {module:engine/model/position~Position} Transformed position.
  688. */
  689. _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
  690. // Update target position, as it could be affected by nodes removal.
  691. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  692. if ( sourcePosition.isEqual( targetPosition ) ) {
  693. // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
  694. return Position._createAt( this );
  695. }
  696. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  697. const transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  698. const isMoved = transformed === null ||
  699. ( sourcePosition.isEqual( this ) && this.stickiness == 'toNext' ) ||
  700. ( sourcePosition.getShiftedBy( howMany ).isEqual( this ) && this.stickiness == 'toPrevious' );
  701. if ( isMoved ) {
  702. // This position is inside moved range (or sticks to it).
  703. // In this case, we calculate a combination of this position, move source position and target position.
  704. return this._getCombined( sourcePosition, targetPosition );
  705. } else {
  706. // This position is not inside a removed range.
  707. //
  708. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  709. return transformed._getTransformedByInsertion( targetPosition, howMany );
  710. }
  711. }
  712. /**
  713. * Returns a new position that is a combination of this position and given positions.
  714. *
  715. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  716. * to the `target` position. It is expected that this position is inside the moved range.
  717. *
  718. * Example:
  719. *
  720. * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
  721. * let source = model.createPositionFromPath( root, [ 2, 2 ] );
  722. * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
  723. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  724. *
  725. * Explanation:
  726. *
  727. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  728. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  729. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  730. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  731. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  732. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  733. *
  734. * @protected
  735. * @param {module:engine/model/position~Position} source Beginning of the moved range.
  736. * @param {module:engine/model/position~Position} target Position where the range is moved.
  737. * @returns {module:engine/model/position~Position} Combined position.
  738. */
  739. _getCombined( source, target ) {
  740. const i = source.path.length - 1;
  741. // The first part of a path to combined position is a path to the place where nodes were moved.
  742. const combined = Position._createAt( target );
  743. combined.stickiness = this.stickiness;
  744. // Then we have to update the rest of the path.
  745. // Fix the offset because this position might be after `from` position and we have to reflect that.
  746. combined.offset = combined.offset + this.path[ i ] - source.offset;
  747. // Then, add the rest of the path.
  748. // If this position is at the same level as `from` position nothing will get added.
  749. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  750. return combined;
  751. }
  752. /**
  753. * @inheritDoc
  754. */
  755. toJSON() {
  756. return {
  757. root: this.root.toJSON(),
  758. path: Array.from( this.path ),
  759. stickiness: this.stickiness
  760. };
  761. }
  762. /**
  763. * Returns a new position that is equal to current position.
  764. *
  765. * @returns {module:engine/model/position~Position}
  766. */
  767. clone() {
  768. return new this.constructor( this.root, this.path, this.stickiness );
  769. }
  770. /**
  771. * Creates position at the given location. The location can be specified as:
  772. *
  773. * * a {@link module:engine/model/position~Position position},
  774. * * parent element and offset (offset defaults to `0`),
  775. * * parent element and `'end'` (sets position at the end of that element),
  776. * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  777. *
  778. * This method is a shortcut to other factory methods such as:
  779. *
  780. * * {@link module:engine/model/position~Position._createBefore},
  781. * * {@link module:engine/model/position~Position._createAfter}.
  782. *
  783. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  784. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when the
  785. * first parameter is a {@link module:engine/model/item~Item model item}.
  786. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness. Used only when the
  787. * first parameter is a {@link module:engine/model/item~Item model item}.
  788. * @protected
  789. */
  790. static _createAt( itemOrPosition, offset, stickiness = 'toNone' ) {
  791. if ( itemOrPosition instanceof Position ) {
  792. return new Position( itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness );
  793. } else {
  794. const node = itemOrPosition;
  795. if ( offset == 'end' ) {
  796. offset = node.maxOffset;
  797. } else if ( offset == 'before' ) {
  798. return this._createBefore( node, stickiness );
  799. } else if ( offset == 'after' ) {
  800. return this._createAfter( node, stickiness );
  801. } else if ( offset !== 0 && !offset ) {
  802. /**
  803. * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
  804. * requires the offset to be specified when the first parameter is a model item.
  805. *
  806. * @error model-createPositionAt-offset-required
  807. */
  808. throw new CKEditorError(
  809. 'model-createPositionAt-offset-required: ' +
  810. 'Model#createPositionAt() requires the offset when the first parameter is a model item.',
  811. [ this, itemOrPosition ]
  812. );
  813. }
  814. if ( !node.is( 'element' ) && !node.is( 'documentFragment' ) ) {
  815. /**
  816. * Position parent have to be a model element or model document fragment.
  817. *
  818. * @error model-position-parent-incorrect
  819. */
  820. throw new CKEditorError(
  821. 'model-position-parent-incorrect: Position parent have to be a element or document fragment.',
  822. [ this, itemOrPosition ]
  823. );
  824. }
  825. const path = node.getPath();
  826. path.push( offset );
  827. return new this( node.root, path, stickiness );
  828. }
  829. }
  830. /**
  831. * Creates a new position, after given {@link module:engine/model/item~Item model item}.
  832. *
  833. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  834. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  835. * @returns {module:engine/model/position~Position}
  836. * @protected
  837. */
  838. static _createAfter( item, stickiness ) {
  839. if ( !item.parent ) {
  840. /**
  841. * You can not make a position after a root element.
  842. *
  843. * @error model-position-after-root
  844. * @param {module:engine/model/item~Item} root
  845. */
  846. throw new CKEditorError(
  847. 'model-position-after-root: You cannot make a position after root.',
  848. [ this, item ],
  849. { root: item }
  850. );
  851. }
  852. return this._createAt( item.parent, item.endOffset, stickiness );
  853. }
  854. /**
  855. * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
  856. *
  857. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  858. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  859. * @returns {module:engine/model/position~Position}
  860. * @protected
  861. */
  862. static _createBefore( item, stickiness ) {
  863. if ( !item.parent ) {
  864. /**
  865. * You can not make a position before a root element.
  866. *
  867. * @error model-position-before-root
  868. * @param {module:engine/model/item~Item} root
  869. */
  870. throw new CKEditorError(
  871. 'model-position-before-root: You cannot make a position before root.',
  872. item,
  873. { root: item }
  874. );
  875. }
  876. return this._createAt( item.parent, item.startOffset, stickiness );
  877. }
  878. /**
  879. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  880. *
  881. * @param {Object} json Plain object to be converted to `Position`.
  882. * @param {module:engine/model/document~Document} doc Document object that will be position owner.
  883. * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
  884. */
  885. static fromJSON( json, doc ) {
  886. if ( json.root === '$graveyard' ) {
  887. const pos = new Position( doc.graveyard, json.path );
  888. pos.stickiness = json.stickiness;
  889. return pos;
  890. }
  891. if ( !doc.getRoot( json.root ) ) {
  892. /**
  893. * Cannot create position for document. Root with specified name does not exist.
  894. *
  895. * @error model-position-fromjson-no-root
  896. * @param {String} rootName
  897. */
  898. throw new CKEditorError(
  899. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  900. doc,
  901. { rootName: json.root }
  902. );
  903. }
  904. return new Position( doc.getRoot( json.root ), json.path, json.stickiness );
  905. }
  906. // @if CK_DEBUG_ENGINE // toString() {
  907. // @if CK_DEBUG_ENGINE // return `${ this.root } [ ${ this.path.join( ', ' ) } ]`;
  908. // @if CK_DEBUG_ENGINE // }
  909. // @if CK_DEBUG_ENGINE // log() {
  910. // @if CK_DEBUG_ENGINE // console.log( 'ModelPosition: ' + this );
  911. // @if CK_DEBUG_ENGINE // }
  912. }
  913. /**
  914. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  915. * If positions are in different roots `'different'` flag is returned.
  916. *
  917. * @typedef {String} module:engine/model/position~PositionRelation
  918. */
  919. /**
  920. * Represents how position is "sticking" with neighbour nodes. Used to define how position should be transformed (moved)
  921. * in edge cases. Possible values: `'toNone'`, `'toNext'`, `'toPrevious'`.
  922. *
  923. * Examples:
  924. *
  925. * Insert. Position is at | and nodes are inserted at the same position, marked as ^:
  926. *
  927. * - sticks to none: <p>f^|oo</p> -> <p>fbar|oo</p>
  928. * - sticks to next node: <p>f^|oo</p> -> <p>fbar|oo</p>
  929. * - sticks to previous node: <p>f|^oo</p> -> <p>f|baroo</p>
  930. *
  931. *
  932. * Move. Position is at | and range [oo] is moved to position ^:
  933. *
  934. * - sticks to none: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  935. * - sticks to none: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  936. *
  937. * - sticks to next node: <p>f|[oo]</p><p>b^ar</p> -> <p>f</p><p>b|ooar</p>
  938. * - sticks to next node: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  939. *
  940. * - sticks to previous node: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
  941. * - sticks to previous node: <p>f[oo]|</p><p>b^ar</p> -> <p>f</p><p>boo|ar</p>
  942. *
  943. * @typedef {String} module:engine/model/position~PositionStickiness
  944. */