position.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import DocumentFragment from './documentfragment.js';
  6. import Element from './element.js';
  7. import last from '../../utils/lib/lodash/last.js';
  8. import compareArrays from '../../utils/comparearrays';
  9. import CKEditorError from '../../utils/ckeditorerror.js';
  10. import Text from './text.js';
  11. /**
  12. * Represents a position in the model tree.
  13. *
  14. * **Note:** Position is based on offsets, not indexes. This means that position in element containing two text nodes
  15. * with data `foo` and `bar`, position between them has offset `3`, not `1`. See {@link engine.model.Position#path} for more.
  16. *
  17. * Since position in a model is represented by a {@link engine.model.Position#root position root} and
  18. * {@link engine.model.Position#path position path} it is possible to create positions placed in non-existing elements.
  19. * This requirement is important for {@link engine.model.operation.transfrom operational transformation}.
  20. *
  21. * Also, {@link engine.model.operation.Operation operations} kept in {@link engine.model.Document#history document history}
  22. * are storing positions (and ranges) which were correct when those operations were applied, but may not be correct
  23. * after document got changed.
  24. *
  25. * When changes are applied to model, it may also happen that {@link engine.model.Position#parent position parent} will change
  26. * even if position path has not changed. Keep in mind, that if a position leads to non-existing element,
  27. * {@link engine.model.Position#parent} and some other properties and methods will throw errors.
  28. *
  29. * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
  30. *
  31. * @memberOf engine.model
  32. */
  33. export default class Position {
  34. /**
  35. * Creates a position.
  36. *
  37. * @param {engine.model.Element|engine.model.DocumentFragment} root Root of the position.
  38. * @param {Array.<Number>} path Position path. See {@link engine.model.Position#path}.
  39. */
  40. constructor( root, path ) {
  41. if ( !( root instanceof Element ) && !( root instanceof DocumentFragment ) ) {
  42. /**
  43. * Position root invalid.
  44. *
  45. * @error position-root-invalid.
  46. */
  47. throw new CKEditorError( 'model-position-root-invalid: Position root invalid.' );
  48. }
  49. if ( !( path instanceof Array ) || path.length === 0 ) {
  50. /**
  51. * Position path must be an Array with at least one item.
  52. *
  53. * @error position-path-incorrect
  54. * @param path
  55. */
  56. throw new CKEditorError( 'model-position-path-incorrect: Position path must be an Array with at least one item.', { path: path } );
  57. }
  58. // Normalize the root and path (if element was passed).
  59. path = root.getPath().concat( path );
  60. root = root.root;
  61. /**
  62. * Root of the position path.
  63. *
  64. * @readonly
  65. * @member {engine.model.Element|engine.model.DocumentFragment} engine.model.Position#root
  66. */
  67. this.root = root;
  68. /**
  69. * Position of the node it the tree. Path is described through offsets, not indexes.
  70. *
  71. * Position can be placed before, after or in a {@link engine.model.Node node} if that node has
  72. * {@link engine.model.Node#offsetSize} greater than `1`. Items in position path are
  73. * {@link engine.model.Node#startOffset starting offsets} of position ancestors, starting from direct root children,
  74. * down to the position offset in it's parent.
  75. *
  76. * ROOT
  77. * |- P before: [ 0 ] after: [ 1 ]
  78. * |- UL before: [ 1 ] after: [ 2 ]
  79. * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
  80. * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
  81. * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
  82. * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
  83. *
  84. * `foo` and `bar` are representing {@link engine.model.Text text nodes}. Since text nodes has offset size
  85. * greater than `1` you can place position offset between their start and end:
  86. *
  87. * ROOT
  88. * |- P
  89. * |- UL
  90. * |- LI
  91. * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
  92. * |- LI
  93. * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
  94. *
  95. * @member {Array.<Number>} engine.model.Position#path
  96. */
  97. this.path = path;
  98. }
  99. /**
  100. * Offset at which this position is located in its {@link engine.model.Position#parent parent}. It is equal
  101. * to the last item in position {@link engine.model.Position#path path}.
  102. *
  103. * @type {Number}
  104. */
  105. get offset() {
  106. return last( this.path );
  107. }
  108. /**
  109. * @param {Number} newOffset
  110. */
  111. set offset( newOffset ) {
  112. this.path[ this.path.length - 1 ] = newOffset;
  113. }
  114. /**
  115. * Parent element of this position.
  116. *
  117. * Keep in mind that `parent` value is calculated when the property is accessed. If {@link engine.model.Position#path position path}
  118. * leads to a non-existing element, `parent` property will throw error.
  119. *
  120. * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
  121. *
  122. * @readonly
  123. * @type {engine.model.Element}
  124. */
  125. get parent() {
  126. let parent = this.root;
  127. for ( let i = 0; i < this.path.length - 1; i++ ) {
  128. parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
  129. }
  130. return parent;
  131. }
  132. /**
  133. * Position {@link engine.model.Position#offset offset} converted to an index in position's parent node. It is
  134. * equal to the {@link engine.model.Node#getIndex index} of a node after this position. If position is placed
  135. * in text node, position index is equal to the index of that text node.
  136. *
  137. * @readonly
  138. * @type {Number}
  139. */
  140. get index() {
  141. return this.parent.offsetToIndex( this.offset );
  142. }
  143. /**
  144. * Returns {@link engine.model.Text text node} instance in which this position is placed or `null` if this
  145. * position is not in a text node.
  146. *
  147. * @readonly
  148. * @type {engine.model.Text|null}
  149. */
  150. get textNode() {
  151. let node = this.parent.getChild( this.index );
  152. return ( node instanceof Text && node.startOffset < this.offset ) ? node : null;
  153. }
  154. /**
  155. * Node directly after this position or `null` if this position is in text node.
  156. *
  157. * @readonly
  158. * @type {engine.model.Node|null}
  159. */
  160. get nodeAfter() {
  161. return this.textNode === null ? this.parent.getChild( this.index ) : null;
  162. }
  163. /**
  164. * Node directly before this position or `null` if this position is in text node.
  165. *
  166. * @readonly
  167. * @type {Node}
  168. */
  169. get nodeBefore() {
  170. return this.textNode === null ? this.parent.getChild( this.index - 1 ) : null;
  171. }
  172. /**
  173. * Is `true` if position is at the beginning of its {@link engine.model.Position#parent parent}, `false` otherwise.
  174. *
  175. * @readonly
  176. * @type {Boolean}
  177. */
  178. get isAtStart() {
  179. return this.offset === 0;
  180. }
  181. /**
  182. * Is `true` if position is at the end of its {@link engine.model.Position#parent parent}, `false` otherwise.
  183. *
  184. * @readonly
  185. * @type {Boolean}
  186. */
  187. get isAtEnd() {
  188. return this.offset == this.parent.maxOffset;
  189. }
  190. /**
  191. * Checks whether this position is before or after given position.
  192. *
  193. * @param {engine.model.Position} otherPosition Position to compare with.
  194. * @returns {engine.model.PositionRelation}
  195. */
  196. compareWith( otherPosition ) {
  197. if ( this.root != otherPosition.root ) {
  198. return 'different';
  199. }
  200. const result = compareArrays( this.path, otherPosition.path );
  201. switch ( result ) {
  202. case 'same':
  203. return 'same';
  204. case 'prefix':
  205. return 'before';
  206. case 'extension':
  207. return 'after';
  208. default:
  209. if ( this.path[ result ] < otherPosition.path[ result ] ) {
  210. return 'before';
  211. } else {
  212. return 'after';
  213. }
  214. }
  215. }
  216. /**
  217. * Returns a path to this position's parent. Parent path is equal to position {@link engine.model.Position#path path}
  218. * but without the last item.
  219. *
  220. * This method returns the parent path even if the parent does not exists.
  221. *
  222. * @returns {Array.<Number>} Path to the parent.
  223. */
  224. getParentPath() {
  225. return this.path.slice( 0, -1 );
  226. }
  227. /**
  228. * Returns ancestors array of this position, that is this position's parent and it's ancestors.
  229. *
  230. * @returns {Array.<engine.model.Item>} Array with ancestors.
  231. */
  232. getAncestors() {
  233. return this.parent.getAncestors( { includeNode: true, parentFirst: true } );
  234. }
  235. /**
  236. * Returns a new instance of `Position`, that has same {@link engine.model.Position#parent parent} but it's offset
  237. * is shifted by `shift` value (can be a negative value).
  238. *
  239. * @param {Number} shift Offset shift. Can be a negative value.
  240. * @returns {engine.model.Position} Shifted position.
  241. */
  242. getShiftedBy( shift ) {
  243. let shifted = Position.createFromPosition( this );
  244. let offset = shifted.offset + shift;
  245. shifted.offset = offset < 0 ? 0 : offset;
  246. return shifted;
  247. }
  248. /**
  249. * Checks whether this position is after given position.
  250. *
  251. * @see engine.model.Position#isBefore
  252. *
  253. * @param {engine.model.Position} otherPosition Position to compare with.
  254. * @returns {Boolean} True if this position is after given position.
  255. */
  256. isAfter( otherPosition ) {
  257. return this.compareWith( otherPosition ) == 'after';
  258. }
  259. /**
  260. * Checks whether this position is before given position.
  261. *
  262. * **Note:** watch out when using negation of the value returned by this method, because the negation will also
  263. * be `true` if positions are in different roots and you might not expect this. You should probably use
  264. * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
  265. * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
  266. *
  267. * if ( a.isBefore( b ) && c.isAfter( d ) ) {
  268. * // do A.
  269. * } else {
  270. * // do B.
  271. * }
  272. *
  273. * or, if you have only one if-branch:
  274. *
  275. * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
  276. * // do B.
  277. * }
  278. *
  279. * rather than:
  280. *
  281. * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
  282. * // do B.
  283. * } else {
  284. * // do A.
  285. * }
  286. *
  287. * @param {engine.model.Position} otherPosition Position to compare with.
  288. * @returns {Boolean} True if this position is before given position.
  289. */
  290. isBefore( otherPosition ) {
  291. return this.compareWith( otherPosition ) == 'before';
  292. }
  293. /**
  294. * Checks whether this position is equal to given position.
  295. *
  296. * @param {engine.model.Position} otherPosition Position to compare with.
  297. * @returns {Boolean} True if positions are same.
  298. */
  299. isEqual( otherPosition ) {
  300. return this.compareWith( otherPosition ) == 'same';
  301. }
  302. /**
  303. * Checks whether this position is touching given position. Positions touch when there are no text nodes
  304. * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
  305. * they are very similar or even indistinguishable.
  306. *
  307. * @param {engine.model.Position} otherPosition Position to compare with.
  308. * @returns {Boolean} True if positions touch.
  309. */
  310. isTouching( otherPosition ) {
  311. let left = null;
  312. let right = null;
  313. let compare = this.compareWith( otherPosition );
  314. switch ( compare ) {
  315. case 'same':
  316. return true;
  317. case 'before':
  318. left = Position.createFromPosition( this );
  319. right = Position.createFromPosition( otherPosition );
  320. break;
  321. case 'after':
  322. left = Position.createFromPosition( otherPosition );
  323. right = Position.createFromPosition( this );
  324. break;
  325. default:
  326. return false;
  327. }
  328. // Cached for optimization purposes.
  329. let leftParent = left.parent;
  330. while ( left.path.length + right.path.length ) {
  331. if ( left.isEqual( right ) ) {
  332. return true;
  333. }
  334. if ( left.path.length > right.path.length ) {
  335. if ( left.offset !== leftParent.maxOffset ) {
  336. return false;
  337. }
  338. left.path = left.path.slice( 0, -1 );
  339. leftParent = leftParent.parent;
  340. left.offset++;
  341. } else {
  342. if ( right.offset !== 0 ) {
  343. return false;
  344. }
  345. right.path = right.path.slice( 0, -1 );
  346. }
  347. }
  348. }
  349. /**
  350. * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
  351. * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
  352. *
  353. * @protected
  354. * @param {engine.model.Position} deletePosition Position before the first removed node.
  355. * @param {Number} howMany How many nodes are removed.
  356. * @returns {engine.model.Position|null} Transformed position or `null`.
  357. */
  358. _getTransformedByDeletion( deletePosition, howMany ) {
  359. let transformed = Position.createFromPosition( this );
  360. // This position can't be affected if deletion was in a different root.
  361. if ( this.root != deletePosition.root ) {
  362. return transformed;
  363. }
  364. if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  365. // If nodes are removed from the node that is pointed by this position...
  366. if ( deletePosition.offset < this.offset ) {
  367. // And are removed from before an offset of that position...
  368. if ( deletePosition.offset + howMany > this.offset ) {
  369. // Position is in removed range, it's no longer in the tree.
  370. return null;
  371. } else {
  372. // Decrement the offset accordingly.
  373. transformed.offset -= howMany;
  374. }
  375. }
  376. } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  377. // If nodes are removed from a node that is on a path to this position...
  378. const i = deletePosition.path.length - 1;
  379. if ( deletePosition.offset <= this.path[ i ] ) {
  380. // And are removed from before next node of that path...
  381. if ( deletePosition.offset + howMany > this.path[ i ] ) {
  382. // If the next node of that path is removed return null
  383. // because the node containing this position got removed.
  384. return null;
  385. } else {
  386. // Otherwise, decrement index on that path.
  387. transformed.path[ i ] -= howMany;
  388. }
  389. }
  390. }
  391. return transformed;
  392. }
  393. /**
  394. * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
  395. *
  396. * @protected
  397. * @param {engine.model.Position} insertPosition Position where nodes are inserted.
  398. * @param {Number} howMany How many nodes are inserted.
  399. * @param {Boolean} insertBefore Flag indicating whether nodes are inserted before or after `insertPosition`.
  400. * This is important only when `insertPosition` and this position are same. If that is the case and the flag is
  401. * set to `true`, this position will get transformed. If the flag is set to `false`, it won't.
  402. * @returns {engine.model.Position} Transformed position.
  403. */
  404. _getTransformedByInsertion( insertPosition, howMany, insertBefore ) {
  405. let transformed = Position.createFromPosition( this );
  406. // This position can't be affected if insertion was in a different root.
  407. if ( this.root != insertPosition.root ) {
  408. return transformed;
  409. }
  410. if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
  411. // If nodes are inserted in the node that is pointed by this position...
  412. if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && insertBefore ) ) {
  413. // And are inserted before an offset of that position...
  414. // "Push" this positions offset.
  415. transformed.offset += howMany;
  416. }
  417. } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
  418. // If nodes are inserted in a node that is on a path to this position...
  419. const i = insertPosition.path.length - 1;
  420. if ( insertPosition.offset <= this.path[ i ] ) {
  421. // And are inserted before next node of that path...
  422. // "Push" the index on that path.
  423. transformed.path[ i ] += howMany;
  424. }
  425. }
  426. return transformed;
  427. }
  428. /**
  429. * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
  430. *
  431. * @protected
  432. * @param {engine.model.Position} sourcePosition Position before the first element to move.
  433. * @param {engine.model.Position} targetPosition Position where moved elements will be inserted.
  434. * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
  435. * @param {Boolean} insertBefore Flag indicating whether moved nodes are pasted before or after `insertPosition`.
  436. * This is important only when `targetPosition` and this position are same. If that is the case and the flag is
  437. * set to `true`, this position will get transformed by range insertion. If the flag is set to `false`, it won't.
  438. * @param {Boolean} [sticky] Flag indicating whether this position "sticks" to range, that is if it should be moved
  439. * with the moved range if it is equal to one of range's boundaries.
  440. * @returns {engine.model.Position} Transformed position.
  441. */
  442. _getTransformedByMove( sourcePosition, targetPosition, howMany, insertBefore, sticky ) {
  443. // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
  444. let transformed = this._getTransformedByDeletion( sourcePosition, howMany );
  445. // Then we update target position, as it could be affected by nodes removal too.
  446. targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
  447. if ( transformed === null || ( sticky && transformed.isEqual( sourcePosition ) ) ) {
  448. // This position is inside moved range (or sticks to it).
  449. // In this case, we calculate a combination of this position, move source position and target position.
  450. transformed = this._getCombined( sourcePosition, targetPosition );
  451. } else {
  452. // This position is not inside a removed range.
  453. // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
  454. transformed = transformed._getTransformedByInsertion( targetPosition, howMany, insertBefore );
  455. }
  456. return transformed;
  457. }
  458. /**
  459. * Returns a new position that is a combination of this position and given positions.
  460. *
  461. * The combined position is a copy of this position transformed by moving a range starting at `source` position
  462. * to the `target` position. It is expected that this position is inside the moved range.
  463. *
  464. * Example:
  465. *
  466. * let original = new Position( root, [ 2, 3, 1 ] );
  467. * let source = new Position( root, [ 2, 2 ] );
  468. * let target = new Position( otherRoot, [ 1, 1, 3 ] );
  469. * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
  470. *
  471. * Explanation:
  472. *
  473. * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
  474. * was inside moved nodes and now should point to the new place. The moved nodes will be after
  475. * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
  476. * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
  477. * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
  478. * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
  479. *
  480. * @protected
  481. * @param {engine.model.Position} source Beginning of the moved range.
  482. * @param {engine.model.Position} target Position where the range is moved.
  483. * @returns {engine.model.Position} Combined position.
  484. */
  485. _getCombined( source, target ) {
  486. const i = source.path.length - 1;
  487. // The first part of a path to combined position is a path to the place where nodes were moved.
  488. let combined = Position.createFromPosition( target );
  489. // Then we have to update the rest of the path.
  490. // Fix the offset because this position might be after `from` position and we have to reflect that.
  491. combined.offset = combined.offset + this.path[ i ] - source.offset;
  492. // Then, add the rest of the path.
  493. // If this position is at the same level as `from` position nothing will get added.
  494. combined.path = combined.path.concat( this.path.slice( i + 1 ) );
  495. return combined;
  496. }
  497. /**
  498. * Creates position at the given location. The location can be specified as:
  499. *
  500. * * a {@link engine.model.Position position},
  501. * * parent element and offset (offset defaults to `0`),
  502. * * parent element and `'end'` (sets position at the end of that element),
  503. * * {@link engine.model.Item model item} and `'before'` or `'after'` (sets position before or after given model item).
  504. *
  505. * This method is a shortcut to other constructors such as:
  506. *
  507. * * {@link engine.model.Position.createBefore},
  508. * * {@link engine.model.Position.createAfter},
  509. * * {@link engine.model.Position.createFromParentAndOffset},
  510. * * {@link engine.model.Position.createFromPosition}.
  511. *
  512. * @param {engine.model.Item|engine.model.Position} itemOrPosition
  513. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  514. * first parameter is a {@link engine.model.Item model item}.
  515. */
  516. static createAt( itemOrPosition, offset ) {
  517. if ( itemOrPosition instanceof Position ) {
  518. return this.createFromPosition( itemOrPosition );
  519. } else {
  520. const node = itemOrPosition;
  521. if ( offset == 'end' ) {
  522. offset = node.maxOffset;
  523. } else if ( offset == 'before' ) {
  524. return this.createBefore( node );
  525. } else if ( offset == 'after' ) {
  526. return this.createAfter( node );
  527. } else if ( !offset ) {
  528. offset = 0;
  529. }
  530. return this.createFromParentAndOffset( node, offset );
  531. }
  532. }
  533. /**
  534. * Creates a new position, after given {@link engine.model.Item model item}.
  535. *
  536. * @param {engine.model.Item} item Item after which the position should be placed.
  537. * @returns {engine.model.Position}
  538. */
  539. static createAfter( item ) {
  540. if ( !item.parent ) {
  541. /**
  542. * You can not make position after root.
  543. *
  544. * @error position-after-root
  545. * @param {engine.model.Item} root
  546. */
  547. throw new CKEditorError( 'model-position-after-root: You can not make position after root.', { root: item } );
  548. }
  549. return this.createFromParentAndOffset( item.parent, item.endOffset );
  550. }
  551. /**
  552. * Creates a new position, before the given {@link engine.model.Item model item}.
  553. *
  554. * @param {engine.model.Item} item Item before which the position should be placed.
  555. * @returns {engine.model.Position}
  556. */
  557. static createBefore( item ) {
  558. if ( !item.parent ) {
  559. /**
  560. * You can not make position before root.
  561. *
  562. * @error position-before-root
  563. * @param {engine.model.Item} root
  564. */
  565. throw new CKEditorError( 'model-position-before-root: You can not make position before root.', { root: item } );
  566. }
  567. return this.createFromParentAndOffset( item.parent, item.startOffset );
  568. }
  569. /**
  570. * Creates a new position from the parent element and an offset in that element.
  571. *
  572. * @param {engine.model.Element|engine.model.DocumentFragment} parent Position's parent.
  573. * @param {Number} offset Position's offset.
  574. * @returns {engine.model.Position}
  575. */
  576. static createFromParentAndOffset( parent, offset ) {
  577. if ( !( parent instanceof Element || parent instanceof DocumentFragment ) ) {
  578. /**
  579. * Position parent have to be a model element or model document fragment.
  580. *
  581. * @error position-parent-incorrect
  582. */
  583. throw new CKEditorError( 'model-position-parent-incorrect: Position parent have to be a element or document fragment.' );
  584. }
  585. const path = parent.getPath();
  586. path.push( offset );
  587. return new this( parent.root, path );
  588. }
  589. /**
  590. * Creates a new position, which is equal to passed position.
  591. *
  592. * @param {engine.model.Position} position Position to be cloned.
  593. * @returns {engine.model.Position}
  594. */
  595. static createFromPosition( position ) {
  596. return new this( position.root, position.path.slice() );
  597. }
  598. /**
  599. * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
  600. *
  601. * @param {Object} json Plain object to be converted to `Position`.
  602. * @returns {engine.model.Position} `Position` instance created using given plain object.
  603. */
  604. static fromJSON( json, doc ) {
  605. if ( json.root === '$graveyard' ) {
  606. return new Position( doc.graveyard, json.path );
  607. }
  608. if ( !doc.hasRoot( json.root ) ) {
  609. /**
  610. * Cannot create position for document. Root with specified name does not exist.
  611. *
  612. * @error position-fromjson-no-root
  613. * @param {String} rootName
  614. */
  615. throw new CKEditorError(
  616. 'model-position-fromjson-no-root: Cannot create position for document. Root with specified name does not exist.',
  617. { rootName: json.root }
  618. );
  619. }
  620. return new Position( doc.getRoot( json.root ), json.path );
  621. }
  622. }
  623. /**
  624. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  625. * If positions are in different roots `'different'` flag is returned.
  626. *
  627. * @typedef {String} engine.model.PositionRelation
  628. */