8
0

selection.js 29 KB

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