8
0

position.js 39 KB

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