8
0

position.js 13 KB

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