8
0

selection.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/selection
  7. */
  8. import Position from './position';
  9. import Element from './element';
  10. import Node from './node';
  11. import Range from './range';
  12. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  13. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  14. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  15. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  16. /**
  17. * `Selection` is a group of {@link module:engine/model/range~Range ranges} which has a direction specified by
  18. * {@link module:engine/model/selection~Selection#anchor anchor} and {@link module:engine/model/selection~Selection#focus focus}.
  19. * Additionally, `Selection` may have it's own attributes.
  20. *
  21. * @mixes {module:utils/emittermixin~EmitterMixin}
  22. */
  23. export default class Selection {
  24. /**
  25. * Creates new selection instance on the given
  26. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  27. * {@link module:engine/model/element~Element element}, {@link module:engine/model/position~Position position},
  28. * {@link module:engine/model/range~Range range}, an iterable of {@link module:engine/model/range~Range ranges}
  29. * or creates an empty selection if no arguments passed.
  30. *
  31. * // Creates empty selection without ranges.
  32. * const selection = new Selection();
  33. *
  34. * // Creates selection at the given range.
  35. * const range = new Range( start, end );
  36. * const selection = new Selection( range, { backward } );
  37. *
  38. * // Creates selection at the given ranges
  39. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  40. * const selection = new Selection( ranges, { backward } );
  41. *
  42. * // Creates selection from the other selection.
  43. * // Note: It doesn't copies selection attributes.
  44. * const otherSelection = new Selection();
  45. * const selection = new Selection( otherSelection );
  46. *
  47. * // Creates selection from the given document selection.
  48. * // Note: It doesn't copies selection attributes.
  49. * const documentSelection = new DocumentSelection( doc );
  50. * const selection = new Selection( documentSelection );
  51. *
  52. * // Creates selection at the given position.
  53. * const position = new Position( root, path );
  54. * const selection = new Selection( position );
  55. *
  56. * // Creates selection inside the node.
  57. * const paragraph = writer.createElement( 'paragraph' );
  58. * selection.setTo( paragraph, 'in', { backward } );
  59. *
  60. * // Creates selection on the node.
  61. * const paragraph = writer.createElement( 'paragraph' );
  62. * selection.setTo( paragraph, 'on', { backward } );
  63. *
  64. * // Creates selection at the start position of the given element.
  65. * const paragraph = writer.createElement( 'paragraph' );
  66. * const selection = new Selection( paragraph, offset );
  67. *
  68. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  69. * module:engine/model/position~Position|module:engine/model/element~Element|
  70. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range|null} selectable
  71. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset]
  72. * @param {Object} [options]
  73. * @param {Boolean} [options.backward]
  74. */
  75. constructor( selectable, placeOrOffset, options ) {
  76. /**
  77. * Specifies whether the last added range was added as a backward or forward range.
  78. *
  79. * @private
  80. * @type {Boolean}
  81. */
  82. this._lastRangeBackward = false;
  83. /**
  84. * Stores selection ranges.
  85. *
  86. * @protected
  87. * @type {Array.<module:engine/model/range~Range>}
  88. */
  89. this._ranges = [];
  90. /**
  91. * List of attributes set on current selection.
  92. *
  93. * @protected
  94. * @type {Map.<String,*>}
  95. */
  96. this._attrs = new Map();
  97. if ( selectable ) {
  98. this.setTo( selectable, placeOrOffset, options );
  99. }
  100. }
  101. /**
  102. * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
  103. * Together with {@link #focus} they define the direction of selection, which is important
  104. * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
  105. * {@link module:engine/model/range~Range#end end} position of the most recently added range.
  106. *
  107. * Is set to `null` if there are no ranges in selection.
  108. *
  109. * @see #focus
  110. * @readonly
  111. * @type {module:engine/model/position~Position|null}
  112. */
  113. get anchor() {
  114. if ( this._ranges.length > 0 ) {
  115. const range = this._ranges[ this._ranges.length - 1 ];
  116. return this._lastRangeBackward ? range.end : range.start;
  117. }
  118. return null;
  119. }
  120. /**
  121. * Selection focus. Focus is a position where the selection ends.
  122. *
  123. * Is set to `null` if there are no ranges in selection.
  124. *
  125. * @see #anchor
  126. * @readonly
  127. * @type {module:engine/model/position~Position|null}
  128. */
  129. get focus() {
  130. if ( this._ranges.length > 0 ) {
  131. const range = this._ranges[ this._ranges.length - 1 ];
  132. return this._lastRangeBackward ? range.start : range.end;
  133. }
  134. return null;
  135. }
  136. /**
  137. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  138. * collapsed.
  139. *
  140. * @readonly
  141. * @type {Boolean}
  142. */
  143. get isCollapsed() {
  144. const length = this._ranges.length;
  145. if ( length === 1 ) {
  146. return this._ranges[ 0 ].isCollapsed;
  147. } else {
  148. return false;
  149. }
  150. }
  151. /**
  152. * Returns number of ranges in selection.
  153. *
  154. * @readonly
  155. * @type {Number}
  156. */
  157. get rangeCount() {
  158. return this._ranges.length;
  159. }
  160. /**
  161. * Specifies whether the {@link #focus}
  162. * precedes {@link #anchor}.
  163. *
  164. * @readonly
  165. * @type {Boolean}
  166. */
  167. get isBackward() {
  168. return !this.isCollapsed && this._lastRangeBackward;
  169. }
  170. /**
  171. * Checks whether this selection is equal to given selection. Selections are equal if they have same directions,
  172. * same number of ranges and all ranges from one selection equal to a range from other selection.
  173. *
  174. * @param {module:engine/model/selection~Selection} otherSelection Selection to compare with.
  175. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  176. */
  177. isEqual( otherSelection ) {
  178. if ( this.rangeCount != otherSelection.rangeCount ) {
  179. return false;
  180. } else if ( this.rangeCount === 0 ) {
  181. return true;
  182. }
  183. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  184. return false;
  185. }
  186. for ( const thisRange of this._ranges ) {
  187. let found = false;
  188. for ( const otherRange of otherSelection._ranges ) {
  189. if ( thisRange.isEqual( otherRange ) ) {
  190. found = true;
  191. break;
  192. }
  193. }
  194. if ( !found ) {
  195. return false;
  196. }
  197. }
  198. return true;
  199. }
  200. /**
  201. * Returns an iterable that iterates over copies of selection ranges.
  202. *
  203. * @returns {Iterable.<module:engine/model/range~Range>}
  204. */
  205. * getRanges() {
  206. for ( const range of this._ranges ) {
  207. yield Range.createFromRange( range );
  208. }
  209. }
  210. /**
  211. * Returns a copy of the first range in the selection.
  212. * First range is the one which {@link module:engine/model/range~Range#start start} position
  213. * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
  214. * (not to confuse with the first range added to the selection).
  215. *
  216. * Returns `null` if there are no ranges in selection.
  217. *
  218. * @returns {module:engine/model/range~Range|null}
  219. */
  220. getFirstRange() {
  221. let first = null;
  222. for ( const range of this._ranges ) {
  223. if ( !first || range.start.isBefore( first.start ) ) {
  224. first = range;
  225. }
  226. }
  227. return first ? Range.createFromRange( first ) : null;
  228. }
  229. /**
  230. * Returns a copy of the last range in the selection.
  231. * Last range is the one which {@link module:engine/model/range~Range#end end} position
  232. * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
  233. * recently added to the selection).
  234. *
  235. * Returns `null` if there are no ranges in selection.
  236. *
  237. * @returns {module:engine/model/range~Range|null}
  238. */
  239. getLastRange() {
  240. let last = null;
  241. for ( const range of this._ranges ) {
  242. if ( !last || range.end.isAfter( last.end ) ) {
  243. last = range;
  244. }
  245. }
  246. return last ? Range.createFromRange( last ) : null;
  247. }
  248. /**
  249. * Returns the first position in the selection.
  250. * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
  251. * any other position in the selection.
  252. *
  253. * Returns `null` if there are no ranges in selection.
  254. *
  255. * @returns {module:engine/model/position~Position|null}
  256. */
  257. getFirstPosition() {
  258. const first = this.getFirstRange();
  259. return first ? Position.createFromPosition( first.start ) : null;
  260. }
  261. /**
  262. * Returns the last position in the selection.
  263. * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
  264. * any other position in the selection.
  265. *
  266. * Returns `null` if there are no ranges in selection.
  267. *
  268. * @returns {module:engine/model/position~Position|null}
  269. */
  270. getLastPosition() {
  271. const lastRange = this.getLastRange();
  272. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  273. }
  274. /**
  275. * Sets this selection's ranges and direction to the specified location based on the given
  276. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  277. * {@link module:engine/model/element~Element element}, {@link module:engine/model/position~Position position},
  278. * {@link module:engine/model/range~Range range}, an iterable of {@link module:engine/model/range~Range ranges} or null.
  279. *
  280. * // Sets selection to the given range.
  281. * const range = new Range( start, end );
  282. * selection.setTo( range, { backward } );
  283. *
  284. * // Sets selection to given ranges.
  285. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  286. * selection.setTo( ranges, { backward } );
  287. *
  288. * // Sets selection to other selection.
  289. * // Note: It doesn't copies selection attributes.
  290. * const otherSelection = new Selection();
  291. * selection.setTo( otherSelection );
  292. *
  293. * // Sets selection to the given document selection.
  294. * // Note: It doesn't copies selection attributes.
  295. * const documentSelection = new DocumentSelection( doc );
  296. * selection.setTo( documentSelection );
  297. *
  298. * // Sets collapsed selection at the given position.
  299. * const position = new Position( root, path );
  300. * selection.setTo( position );
  301. *
  302. * // Sets collapsed selection at the position of the given node and an offset.
  303. * selection.setTo( paragraph, offset );
  304. *
  305. * // Sets selection inside the given node.
  306. * selection.setTo( paragraph, 'in', { backward } );
  307. *
  308. * // Sets selection on the given node.
  309. * selection.setTo( paragraph, 'on', { backward } );
  310. *
  311. * // Removes all selection's ranges.
  312. * selection.setTo( null );
  313. *
  314. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  315. * module:engine/model/position~Position|module:engine/model/node~Node|
  316. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range|null} selectable
  317. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  318. * @param {Object} [options]
  319. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  320. */
  321. setTo( selectable, placeOrOffset, options ) {
  322. if ( selectable === null ) {
  323. this._setRanges( [] );
  324. } else if ( selectable instanceof Selection ) {
  325. this._setRanges( selectable.getRanges(), selectable.isBackward );
  326. } else if ( selectable && typeof selectable.getRanges == 'function' ) {
  327. // We assume that the selectable is a DocumentSelection.
  328. // It can't be imported here, because it would lead to circular imports.
  329. this._setRanges( selectable.getRanges(), selectable.isBackward );
  330. } else if ( selectable instanceof Range ) {
  331. this._setRanges( [ selectable ], !!placeOrOffset && !!placeOrOffset.backward );
  332. } else if ( selectable instanceof Position ) {
  333. this._setRanges( [ new Range( selectable ) ] );
  334. } else if ( selectable instanceof Node ) {
  335. const backward = !!options && !!options.backward;
  336. let range;
  337. if ( placeOrOffset == 'in' ) {
  338. range = Range.createIn( selectable );
  339. } else if ( placeOrOffset == 'on' ) {
  340. range = Range.createOn( selectable );
  341. } else if ( placeOrOffset !== undefined ) {
  342. range = Range.createCollapsedAt( selectable, placeOrOffset );
  343. } else {
  344. /**
  345. * selection.setTo requires the second parameter when the first parameter is a node.
  346. *
  347. * @error model-selection-setTo-required-second-parameter
  348. */
  349. throw new CKEditorError(
  350. 'model-selection-setTo-required-second-parameter: ' +
  351. 'selection.setTo requires the second parameter when the first parameter is a node.' );
  352. }
  353. this._setRanges( [ range ], backward );
  354. } else if ( isIterable( selectable ) ) {
  355. // We assume that the selectable is an iterable of ranges.
  356. this._setRanges( selectable, placeOrOffset && !!placeOrOffset.backward );
  357. } else {
  358. /**
  359. * Cannot set selection to given place.
  360. *
  361. * @error model-selection-setTo-not-selectable
  362. */
  363. throw new CKEditorError( 'model-selection-setTo-not-selectable: Cannot set selection to given place.' );
  364. }
  365. }
  366. /**
  367. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  368. * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
  369. * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made.
  370. *
  371. * @protected
  372. * @fires change:range
  373. * @param {Iterable.<module:engine/model/range~Range>} newRanges Ranges to set.
  374. * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end (`false`)
  375. * or backward - from end to start (`true`).
  376. */
  377. _setRanges( newRanges, isLastBackward = false ) {
  378. newRanges = Array.from( newRanges );
  379. // Check whether there is any range in new ranges set that is different than all already added ranges.
  380. const anyNewRange = newRanges.some( newRange => {
  381. if ( !( newRange instanceof Range ) ) {
  382. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  383. }
  384. return this._ranges.every( oldRange => {
  385. return !oldRange.isEqual( newRange );
  386. } );
  387. } );
  388. // Don't do anything if nothing changed.
  389. if ( newRanges.length === this._ranges.length && !anyNewRange ) {
  390. return;
  391. }
  392. this._removeAllRanges();
  393. for ( const range of newRanges ) {
  394. this._pushRange( range );
  395. }
  396. this._lastRangeBackward = !!isLastBackward;
  397. this.fire( 'change:range', { directChange: true } );
  398. }
  399. /**
  400. * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
  401. *
  402. * The location can be specified in the same form as {@link module:engine/model/position~Position.createAt} parameters.
  403. *
  404. * @fires change:range
  405. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  406. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  407. * first parameter is a {@link module:engine/model/item~Item model item}.
  408. */
  409. setFocus( itemOrPosition, offset ) {
  410. if ( this.anchor === null ) {
  411. /**
  412. * Cannot set selection focus if there are no ranges in selection.
  413. *
  414. * @error model-selection-setFocus-no-ranges
  415. */
  416. throw new CKEditorError(
  417. 'model-selection-setFocus-no-ranges: Cannot set selection focus if there are no ranges in selection.'
  418. );
  419. }
  420. const newFocus = Position.createAt( itemOrPosition, offset );
  421. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  422. return;
  423. }
  424. const anchor = this.anchor;
  425. if ( this._ranges.length ) {
  426. this._popRange();
  427. }
  428. if ( newFocus.compareWith( anchor ) == 'before' ) {
  429. this._pushRange( new Range( newFocus, anchor ) );
  430. this._lastRangeBackward = true;
  431. } else {
  432. this._pushRange( new Range( anchor, newFocus ) );
  433. this._lastRangeBackward = false;
  434. }
  435. this.fire( 'change:range', { directChange: true } );
  436. }
  437. /**
  438. * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
  439. *
  440. * @param {String} key Key of attribute to look for.
  441. * @returns {*} Attribute value or `undefined`.
  442. */
  443. getAttribute( key ) {
  444. return this._attrs.get( key );
  445. }
  446. /**
  447. * Returns iterable that iterates over this selection's attributes.
  448. *
  449. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  450. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  451. *
  452. * @returns {Iterable.<*>}
  453. */
  454. getAttributes() {
  455. return this._attrs.entries();
  456. }
  457. /**
  458. * Returns iterable that iterates over this selection's attribute keys.
  459. *
  460. * @returns {Iterable.<String>}
  461. */
  462. getAttributeKeys() {
  463. return this._attrs.keys();
  464. }
  465. /**
  466. * Checks if the selection has an attribute for given key.
  467. *
  468. * @param {String} key Key of attribute to check.
  469. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  470. */
  471. hasAttribute( key ) {
  472. return this._attrs.has( key );
  473. }
  474. /**
  475. * Removes an attribute with given key from the selection.
  476. *
  477. * If given attribute was set on the selection, fires the {@link #event:change} event with
  478. * removed attribute key.
  479. *
  480. * @fires change:attribute
  481. * @param {String} key Key of attribute to remove.
  482. */
  483. removeAttribute( key ) {
  484. if ( this.hasAttribute( key ) ) {
  485. this._attrs.delete( key );
  486. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  487. }
  488. }
  489. /**
  490. * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
  491. *
  492. * If the attribute value has changed, fires the {@link #event:change} event with
  493. * the attribute key.
  494. *
  495. * @fires change:attribute
  496. * @param {String} key Key of attribute to set.
  497. * @param {*} value Attribute value.
  498. */
  499. setAttribute( key, value ) {
  500. if ( this.getAttribute( key ) !== value ) {
  501. this._attrs.set( key, value );
  502. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  503. }
  504. }
  505. /**
  506. * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
  507. * one range in the selection, and that range contains exactly one element.
  508. * Returns `null` if there is no selected element.
  509. *
  510. * @returns {module:engine/model/element~Element|null}
  511. */
  512. getSelectedElement() {
  513. if ( this.rangeCount !== 1 ) {
  514. return null;
  515. }
  516. const range = this.getFirstRange();
  517. const nodeAfterStart = range.start.nodeAfter;
  518. const nodeBeforeEnd = range.end.nodeBefore;
  519. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  520. }
  521. /**
  522. * Gets elements of type "block" touched by the selection.
  523. *
  524. * This method's result can be used for example to apply block styling to all blocks covered by this selection.
  525. *
  526. * **Note:** `getSelectedBlocks()` always returns the deepest block.
  527. *
  528. * In this case the function will return exactly all 3 paragraphs:
  529. *
  530. * <paragraph>[a</paragraph>
  531. * <quote>
  532. * <paragraph>b</paragraph>
  533. * </quote>
  534. * <paragraph>c]d</paragraph>
  535. *
  536. * In this case the paragraph will also be returned, despite the collapsed selection:
  537. *
  538. * <paragraph>[]a</paragraph>
  539. *
  540. * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
  541. * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
  542. *
  543. * <paragraph>[a</paragraph>
  544. * <paragraph>b</paragraph>
  545. * <paragraph>]c</paragraph> // this block will not be returned
  546. *
  547. * @returns {Iterable.<module:engine/model/element~Element>}
  548. */
  549. * getSelectedBlocks() {
  550. const visited = new WeakSet();
  551. for ( const range of this.getRanges() ) {
  552. const startBlock = getParentBlock( range.start, visited );
  553. if ( startBlock ) {
  554. yield startBlock;
  555. }
  556. for ( const value of range.getWalker() ) {
  557. if ( value.type == 'elementEnd' && isUnvisitedBlockContainer( value.item, visited ) ) {
  558. yield value.item;
  559. }
  560. }
  561. const endBlock = getParentBlock( range.end, visited );
  562. // #984. Don't return the end block if the range ends right at its beginning.
  563. if ( endBlock && !range.end.isTouching( Position.createAt( endBlock ) ) ) {
  564. yield endBlock;
  565. }
  566. }
  567. }
  568. /**
  569. * Checks whether the selection contains the entire content of the given element. This means that selection must start
  570. * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
  571. * touching the element's end.
  572. *
  573. * By default, this method will check whether the entire content of the selection's current root is selected.
  574. * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
  575. *
  576. * @param {module:engine/model/element~Element} [element=this.anchor.root]
  577. * @returns {Boolean}
  578. */
  579. containsEntireContent( element = this.anchor.root ) {
  580. const limitStartPosition = Position.createAt( element );
  581. const limitEndPosition = Position.createAt( element, 'end' );
  582. return limitStartPosition.isTouching( this.getFirstPosition() ) &&
  583. limitEndPosition.isTouching( this.getLastPosition() );
  584. }
  585. /**
  586. * Adds given range to internal {@link #_ranges ranges array}. Throws an error
  587. * if given range is intersecting with any range that is already stored in this selection.
  588. *
  589. * @protected
  590. * @param {module:engine/model/range~Range} range Range to add.
  591. */
  592. _pushRange( range ) {
  593. this._checkRange( range );
  594. this._ranges.push( Range.createFromRange( range ) );
  595. }
  596. /**
  597. * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
  598. *
  599. * @protected
  600. * @param {module:engine/model/range~Range} range Range to check.
  601. */
  602. _checkRange( range ) {
  603. for ( let i = 0; i < this._ranges.length; i++ ) {
  604. if ( range.isIntersecting( this._ranges[ i ] ) ) {
  605. /**
  606. * Trying to add a range that intersects with another range from selection.
  607. *
  608. * @error model-selection-range-intersects
  609. * @param {module:engine/model/range~Range} addedRange Range that was added to the selection.
  610. * @param {module:engine/model/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  611. */
  612. throw new CKEditorError(
  613. 'model-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  614. { addedRange: range, intersectingRange: this._ranges[ i ] }
  615. );
  616. }
  617. }
  618. }
  619. /**
  620. * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
  621. * ensure proper ranges removal.
  622. *
  623. * @protected
  624. */
  625. _removeAllRanges() {
  626. while ( this._ranges.length > 0 ) {
  627. this._popRange();
  628. }
  629. }
  630. /**
  631. * Removes most recently added range from the selection.
  632. *
  633. * @protected
  634. */
  635. _popRange() {
  636. this._ranges.pop();
  637. }
  638. /**
  639. * @event change
  640. */
  641. /**
  642. * Fired whenever selection ranges are changed.
  643. *
  644. * @event change:range
  645. * @param {Boolean} directChange Specifies whether the range change was caused by direct usage of `Selection` API (`true`)
  646. * or by changes done to {@link module:engine/model/document~Document model document}
  647. * using {@link module:engine/model/batch~Batch Batch} API (`false`).
  648. */
  649. /**
  650. * Fired whenever selection attributes are changed.
  651. *
  652. * @event change:attribute
  653. * @param {Boolean} directChange Specifies whether the attributes changed by direct usage of the Selection API (`true`)
  654. * or by changes done to the {@link module:engine/model/document~Document model document}
  655. * using the {@link module:engine/model/batch~Batch Batch} API (`false`).
  656. * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
  657. */
  658. }
  659. mix( Selection, EmitterMixin );
  660. // Checks whether the given element extends $block in the schema and has a parent (is not a root).
  661. // Marks it as already visited.
  662. function isUnvisitedBlockContainer( element, visited ) {
  663. if ( visited.has( element ) ) {
  664. return false;
  665. }
  666. visited.add( element );
  667. return element.document.model.schema.isBlock( element ) && element.parent;
  668. }
  669. // Finds the lowest element in position's ancestors which is a block.
  670. // Marks all ancestors as already visited to not include any of them later on.
  671. function getParentBlock( position, visited ) {
  672. const ancestors = position.parent.getAncestors( { parentFirst: true, includeSelf: true } );
  673. const block = ancestors.find( element => isUnvisitedBlockContainer( element, visited ) );
  674. // Mark all ancestors of this position's parent, because find() might've stopped early and
  675. // the found block may be a child of another block.
  676. ancestors.forEach( element => visited.add( element ) );
  677. return block;
  678. }