position.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/position
  7. */
  8. import TreeWalker from './treewalker';
  9. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import EditableElement from './editableelement';
  12. /**
  13. * Position in the tree. Position is always located before or after a node.
  14. */
  15. export default class Position {
  16. /**
  17. * Creates a position.
  18. *
  19. * @param {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} parent Position parent.
  20. * @param {Number} offset Position offset.
  21. */
  22. constructor( parent, offset ) {
  23. this._parent = parent;
  24. this._offset = offset;
  25. }
  26. /**
  27. * Position parent.
  28. *
  29. * @readonly
  30. * @type {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment}
  31. */
  32. get parent() {
  33. return this._parent;
  34. }
  35. /**
  36. * Position offset.
  37. *
  38. * @readonly
  39. * @type {Number}
  40. */
  41. get offset() {
  42. return this._offset;
  43. }
  44. /**
  45. * Node directly after the position. Equals `null` when there is no node after position or position is located
  46. * inside text node.
  47. *
  48. * @readonly
  49. * @type {module:engine/view/node~Node|null}
  50. */
  51. get nodeAfter() {
  52. if ( this.parent.is( 'text' ) ) {
  53. return null;
  54. }
  55. return this.parent.getChild( this.offset ) || null;
  56. }
  57. /**
  58. * Node directly before the position. Equals `null` when there is no node before position or position is located
  59. * inside text node.
  60. *
  61. * @readonly
  62. * @type {module:engine/view/node~Node|null}
  63. */
  64. get nodeBefore() {
  65. if ( this.parent.is( 'text' ) ) {
  66. return null;
  67. }
  68. return this.parent.getChild( this.offset - 1 ) || null;
  69. }
  70. /**
  71. * Is `true` if position is at the beginning of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
  72. *
  73. * @readonly
  74. * @type {Boolean}
  75. */
  76. get isAtStart() {
  77. return this.offset === 0;
  78. }
  79. /**
  80. * Is `true` if position is at the end of its {@link module:engine/view/position~Position#parent parent}, `false` otherwise.
  81. *
  82. * @readonly
  83. * @type {Boolean}
  84. */
  85. get isAtEnd() {
  86. const endOffset = this.parent.is( 'text' ) ? this.parent.data.length : this.parent.childCount;
  87. return this.offset === endOffset;
  88. }
  89. /**
  90. * Position's root, that is the root of the position's parent element.
  91. *
  92. * @readonly
  93. * @type {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment}
  94. */
  95. get root() {
  96. return this.parent.root;
  97. }
  98. /**
  99. * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this position, or `null` if
  100. * position is not inside an editable element.
  101. *
  102. * @type {module:engine/view/editableelement~EditableElement|null}
  103. */
  104. get editableElement() {
  105. let editable = this.parent;
  106. while ( !( editable instanceof EditableElement ) ) {
  107. if ( editable.parent ) {
  108. editable = editable.parent;
  109. } else {
  110. return null;
  111. }
  112. }
  113. return editable;
  114. }
  115. /**
  116. * Returns a new instance of Position with offset incremented by `shift` value.
  117. *
  118. * @param {Number} shift How position offset should get changed. Accepts negative values.
  119. * @returns {module:engine/view/position~Position} Shifted position.
  120. */
  121. getShiftedBy( shift ) {
  122. const offset = this.offset + shift;
  123. return new Position( this.parent, offset < 0 ? 0 : offset );
  124. }
  125. /**
  126. * Gets the farthest position which matches the callback using
  127. * {@link module:engine/view/treewalker~TreeWalker TreeWalker}.
  128. *
  129. * For example:
  130. *
  131. * getLastMatchingPosition( value => value.type == 'text' ); // <p>{}foo</p> -> <p>foo[]</p>
  132. * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } ); // <p>foo[]</p> -> <p>{}foo</p>
  133. * getLastMatchingPosition( value => false ); // Do not move the position.
  134. *
  135. * @param {Function} skip Callback function. Gets {@link module:engine/view/treewalker~TreeWalkerValue} and should
  136. * return `true` if the value should be skipped or `false` if not.
  137. * @param {Object} options Object with configuration options. See {@link module:engine/view/treewalker~TreeWalker}.
  138. *
  139. * @returns {module:engine/view/position~Position} The position after the last item which matches the `skip` callback test.
  140. */
  141. getLastMatchingPosition( skip, options = {} ) {
  142. options.startPosition = this;
  143. const treeWalker = new TreeWalker( options );
  144. treeWalker.skip( skip );
  145. return treeWalker.position;
  146. }
  147. /**
  148. * Returns ancestors array of this position, that is this position's parent and it's ancestors.
  149. *
  150. * @returns {Array} Array with ancestors.
  151. */
  152. getAncestors() {
  153. if ( this.parent.is( 'documentFragment' ) ) {
  154. return [ this.parent ];
  155. } else {
  156. return this.parent.getAncestors( { includeSelf: true } );
  157. }
  158. }
  159. /**
  160. * Returns a {@link module:engine/view/node~Node} or {@link module:engine/view/documentfragment~DocumentFragment}
  161. * which is a common ancestor of both positions.
  162. *
  163. * @param {module:engine/view/position~Position} position
  164. * @returns {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment|null}
  165. */
  166. getCommonAncestor( position ) {
  167. const ancestorsA = this.getAncestors();
  168. const ancestorsB = position.getAncestors();
  169. let i = 0;
  170. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  171. i++;
  172. }
  173. return i === 0 ? null : ancestorsA[ i - 1 ];
  174. }
  175. /**
  176. * Checks whether this position equals given position.
  177. *
  178. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  179. * @returns {Boolean} True if positions are same.
  180. */
  181. isEqual( otherPosition ) {
  182. return ( this.parent == otherPosition.parent && this.offset == otherPosition.offset );
  183. }
  184. /**
  185. * Checks whether this position is located before given position. When method returns `false` it does not mean that
  186. * this position is after give one. Two positions may be located inside separate roots and in that situation this
  187. * method will still return `false`.
  188. *
  189. * @see module:engine/view/position~Position#isAfter
  190. * @see module:engine/view/position~Position#compareWith
  191. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  192. * @returns {Boolean} Returns `true` if this position is before given position.
  193. */
  194. isBefore( otherPosition ) {
  195. return this.compareWith( otherPosition ) == 'before';
  196. }
  197. /**
  198. * Checks whether this position is located after given position. When method returns `false` it does not mean that
  199. * this position is before give one. Two positions may be located inside separate roots and in that situation this
  200. * method will still return `false`.
  201. *
  202. * @see module:engine/view/position~Position#isBefore
  203. * @see module:engine/view/position~Position#compareWith
  204. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  205. * @returns {Boolean} Returns `true` if this position is after given position.
  206. */
  207. isAfter( otherPosition ) {
  208. return this.compareWith( otherPosition ) == 'after';
  209. }
  210. /**
  211. * Checks whether this position is before, after or in same position that other position. Two positions may be also
  212. * different when they are located in separate roots.
  213. *
  214. * @param {module:engine/view/position~Position} otherPosition Position to compare with.
  215. * @returns {module:engine/view/position~PositionRelation}
  216. */
  217. compareWith( otherPosition ) {
  218. if ( this.isEqual( otherPosition ) ) {
  219. return 'same';
  220. }
  221. // If positions have same parent.
  222. if ( this.parent === otherPosition.parent ) {
  223. return this.offset - otherPosition.offset < 0 ? 'before' : 'after';
  224. }
  225. // Get path from root to position's parent element.
  226. const path = this.getAncestors();
  227. const otherPath = otherPosition.getAncestors();
  228. // Compare both path arrays to find common ancestor.
  229. const result = compareArrays( path, otherPath );
  230. let commonAncestorIndex;
  231. switch ( result ) {
  232. case 0:
  233. // No common ancestors found.
  234. return 'different';
  235. case 'prefix':
  236. commonAncestorIndex = path.length - 1;
  237. break;
  238. case 'extension':
  239. commonAncestorIndex = otherPath.length - 1;
  240. break;
  241. default:
  242. commonAncestorIndex = result - 1;
  243. }
  244. // Common ancestor of two positions.
  245. const commonAncestor = path[ commonAncestorIndex ];
  246. const nextAncestor1 = path[ commonAncestorIndex + 1 ];
  247. const nextAncestor2 = otherPath[ commonAncestorIndex + 1 ];
  248. // Check if common ancestor is not one of the parents.
  249. if ( commonAncestor === this.parent ) {
  250. const index = this.offset - nextAncestor2.index;
  251. return index <= 0 ? 'before' : 'after';
  252. } else if ( commonAncestor === otherPosition.parent ) {
  253. const index = nextAncestor1.index - otherPosition.offset;
  254. return index < 0 ? 'before' : 'after';
  255. }
  256. const index = nextAncestor1.index - nextAncestor2.index;
  257. // Compare indexes of next ancestors inside common one.
  258. return index < 0 ? 'before' : 'after';
  259. }
  260. /**
  261. * Creates position at the given location. The location can be specified as:
  262. *
  263. * * a {@link module:engine/view/position~Position position},
  264. * * parent element and offset (offset defaults to `0`),
  265. * * parent element and `'end'` (sets position at the end of that element),
  266. * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
  267. *
  268. * This method is a shortcut to other constructors such as:
  269. *
  270. * * {@link module:engine/view/position~Position.createBefore},
  271. * * {@link module:engine/view/position~Position.createAfter},
  272. * * {@link module:engine/view/position~Position.createFromPosition}.
  273. *
  274. * @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
  275. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  276. * first parameter is a {@link module:engine/view/item~Item view item}.
  277. */
  278. static createAt( itemOrPosition, offset ) {
  279. if ( itemOrPosition instanceof Position ) {
  280. return this.createFromPosition( itemOrPosition );
  281. } else {
  282. const node = itemOrPosition;
  283. if ( offset == 'end' ) {
  284. offset = node.is( 'text' ) ? node.data.length : node.childCount;
  285. } else if ( offset == 'before' ) {
  286. return this.createBefore( node );
  287. } else if ( offset == 'after' ) {
  288. return this.createAfter( node );
  289. } else if ( !offset ) {
  290. offset = 0;
  291. }
  292. return new Position( node, offset );
  293. }
  294. }
  295. /**
  296. * Creates a new position after given view item.
  297. *
  298. * @param {module:engine/view/item~Item} item View item after which the position should be located.
  299. * @returns {module:engine/view/position~Position}
  300. */
  301. static createAfter( item ) {
  302. // TextProxy is not a instance of Node so we need do handle it in specific way.
  303. if ( item.is( 'textProxy' ) ) {
  304. return new Position( item.textNode, item.offsetInText + item.data.length );
  305. }
  306. if ( !item.parent ) {
  307. /**
  308. * You can not make a position after a root.
  309. *
  310. * @error view-position-after-root
  311. * @param {module:engine/view/node~Node} root
  312. */
  313. throw new CKEditorError( 'view-position-after-root: You can not make position after root.', { root: item } );
  314. }
  315. return new Position( item.parent, item.index + 1 );
  316. }
  317. /**
  318. * Creates a new position before given view item.
  319. *
  320. * @param {module:engine/view/item~Item} item View item before which the position should be located.
  321. * @returns {module:engine/view/position~Position}
  322. */
  323. static createBefore( item ) {
  324. // TextProxy is not a instance of Node so we need do handle it in specific way.
  325. if ( item.is( 'textProxy' ) ) {
  326. return new Position( item.textNode, item.offsetInText );
  327. }
  328. if ( !item.parent ) {
  329. /**
  330. * You cannot make a position before a root.
  331. *
  332. * @error view-position-before-root
  333. * @param {module:engine/view/node~Node} root
  334. */
  335. throw new CKEditorError( 'view-position-before-root: You can not make position before root.', { root: item } );
  336. }
  337. return new Position( item.parent, item.index );
  338. }
  339. /**
  340. * Creates and returns a new instance of `Position`, which is equal to the passed position.
  341. *
  342. * @param {module:engine/view/position~Position} position Position to be cloned.
  343. * @returns {module:engine/view/position~Position}
  344. */
  345. static createFromPosition( position ) {
  346. return new this( position.parent, position.offset );
  347. }
  348. }
  349. /**
  350. * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
  351. * If positions are in different roots `'different'` flag is returned.
  352. *
  353. * @typedef {String} module:engine/view/position~PositionRelation
  354. */