8
0

selection.js 30 KB

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