position.js 13 KB

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