position.js 41 KB

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