8
0

selection.js 26 KB

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