selection.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/selection
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import Range from './range';
  10. import Position from './position';
  11. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  12. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  13. import Element from './element';
  14. import Text from './text';
  15. import count from '@ckeditor/ckeditor5-utils/src/count';
  16. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  17. /**
  18. * Class representing selection in tree view.
  19. *
  20. * Selection can consist of {@link module:engine/view/range~Range ranges} that can be set using
  21. * {@link module:engine/view/selection~Selection#_setTo} method.
  22. * That method create copies of provided ranges and store those copies internally. Further modifications to passed
  23. * ranges will not change selection's state.
  24. * Selection's ranges can be obtained via {@link module:engine/view/selection~Selection#getRanges getRanges},
  25. * {@link module:engine/view/selection~Selection#getFirstRange getFirstRange}
  26. * and {@link module:engine/view/selection~Selection#getLastRange getLastRange}
  27. * methods, which return copies of ranges stored inside selection. Modifications made on these copies will not change
  28. * selection's state. Similar situation occurs when getting {@link module:engine/view/selection~Selection#anchor anchor},
  29. * {@link module:engine/view/selection~Selection#focus focus}, {@link module:engine/view/selection~Selection#getFirstPosition first} and
  30. * {@link module:engine/view/selection~Selection#getLastPosition last} positions - all will return copies of requested positions.
  31. */
  32. export default class Selection {
  33. /**
  34. * Creates new selection instance.
  35. *
  36. * // Creates empty selection without ranges.
  37. * const selection = new Selection();
  38. *
  39. * // Creates selection at the given range.
  40. * const range = new Range( start, end );
  41. * const selection = new Selection( range, isBackwardSelection );
  42. *
  43. * // Creates selection at the given ranges
  44. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  45. * const selection = new Selection( ranges, isBackwardSelection );
  46. *
  47. * // Creates selection from the other selection.
  48. * const otherSelection = new Selection();
  49. * const selection = new Selection( otherSelection );
  50. *
  51. * // Creates selection at the given position.
  52. * const position = new Position( root, path );
  53. * const selection = new Selection( position );
  54. *
  55. * // Creates selection at the start position of given element.
  56. * const paragraph = writer.createElement( 'paragraph' );
  57. * const selection = new Selection( paragraph, offset );
  58. *
  59. * @param {module:engine/view/selection~Selection|module:engine/view/position~Position|
  60. * Iterable.<module:engine/view/range~Range>|module:engine/view/range~Range|module:engine/view/item~Item} [selectable]
  61. * @param {Boolean|Number|'before'|'end'|'after'} [backwardSelectionOrOffset]
  62. */
  63. constructor( selectable, backwardSelectionOrOffset ) {
  64. /**
  65. * Stores all ranges that are selected.
  66. *
  67. * @protected
  68. * @member {Array.<module:engine/view/range~Range>}
  69. */
  70. this._ranges = [];
  71. /**
  72. * Specifies whether the last added range was added as a backward or forward range.
  73. *
  74. * @protected
  75. * @member {Boolean}
  76. */
  77. this._lastRangeBackward = false;
  78. /**
  79. * Specifies whether selection instance is fake.
  80. *
  81. * @private
  82. * @member {Boolean}
  83. */
  84. this._isFake = false;
  85. /**
  86. * Fake selection's label.
  87. *
  88. * @private
  89. * @member {String}
  90. */
  91. this._fakeSelectionLabel = '';
  92. if ( selectable ) {
  93. this._setTo( selectable, backwardSelectionOrOffset );
  94. }
  95. }
  96. /**
  97. * Returns true if selection instance is marked as `fake`.
  98. *
  99. * @see #_setFake
  100. * @returns {Boolean}
  101. */
  102. get isFake() {
  103. return this._isFake;
  104. }
  105. /**
  106. * Returns fake selection label.
  107. *
  108. * @see #_setFake
  109. * @returns {String}
  110. */
  111. get fakeSelectionLabel() {
  112. return this._fakeSelectionLabel;
  113. }
  114. /**
  115. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  116. * {@link #focus focus} they define the direction of selection, which is important
  117. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  118. * It may be a bit unintuitive when there are multiple ranges in selection.
  119. *
  120. * @see #focus
  121. * @type {module:engine/view/position~Position}
  122. */
  123. get anchor() {
  124. if ( !this._ranges.length ) {
  125. return null;
  126. }
  127. const range = this._ranges[ this._ranges.length - 1 ];
  128. const anchor = this._lastRangeBackward ? range.end : range.start;
  129. return Position.createFromPosition( anchor );
  130. }
  131. /**
  132. * Selection focus. Focus is a position where the selection ends.
  133. *
  134. * @see #anchor
  135. * @type {module:engine/view/position~Position}
  136. */
  137. get focus() {
  138. if ( !this._ranges.length ) {
  139. return null;
  140. }
  141. const range = this._ranges[ this._ranges.length - 1 ];
  142. const focus = this._lastRangeBackward ? range.start : range.end;
  143. return Position.createFromPosition( focus );
  144. }
  145. /**
  146. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  147. * collapsed.
  148. *
  149. * @type {Boolean}
  150. */
  151. get isCollapsed() {
  152. return this.rangeCount === 1 && this._ranges[ 0 ].isCollapsed;
  153. }
  154. /**
  155. * Returns number of ranges in selection.
  156. *
  157. * @type {Number}
  158. */
  159. get rangeCount() {
  160. return this._ranges.length;
  161. }
  162. /**
  163. * Specifies whether the {@link #focus} precedes {@link #anchor}.
  164. *
  165. * @type {Boolean}
  166. */
  167. get isBackward() {
  168. return !this.isCollapsed && this._lastRangeBackward;
  169. }
  170. /**
  171. * {@link module:engine/view/editableelement~EditableElement EditableElement} instance that contains this selection, or `null`
  172. * if the selection is not inside an editable element.
  173. *
  174. * @type {module:engine/view/editableelement~EditableElement|null}
  175. */
  176. get editableElement() {
  177. if ( this.anchor ) {
  178. return this.anchor.editableElement;
  179. }
  180. return null;
  181. }
  182. /**
  183. * Returns an iterable that contains copies of all ranges added to the selection.
  184. *
  185. * @returns {Iterable.<module:engine/view/range~Range>}
  186. */
  187. * getRanges() {
  188. for ( const range of this._ranges ) {
  189. yield Range.createFromRange( range );
  190. }
  191. }
  192. /**
  193. * Returns copy of the first range in the selection. First range is the one which
  194. * {@link module:engine/view/range~Range#start start} position {@link module:engine/view/position~Position#isBefore is before} start
  195. * position of all other ranges (not to confuse with the first range added to the selection).
  196. * Returns `null` if no ranges are added to selection.
  197. *
  198. * @returns {module:engine/view/range~Range|null}
  199. */
  200. getFirstRange() {
  201. let first = null;
  202. for ( const range of this._ranges ) {
  203. if ( !first || range.start.isBefore( first.start ) ) {
  204. first = range;
  205. }
  206. }
  207. return first ? Range.createFromRange( first ) : null;
  208. }
  209. /**
  210. * Returns copy of the last range in the selection. Last range is the one which {@link module:engine/view/range~Range#end end}
  211. * position {@link module:engine/view/position~Position#isAfter is after} end position of all other ranges (not to confuse
  212. * with the last range added to the selection). Returns `null` if no ranges are added to selection.
  213. *
  214. * @returns {module:engine/view/range~Range|null}
  215. */
  216. getLastRange() {
  217. let last = null;
  218. for ( const range of this._ranges ) {
  219. if ( !last || range.end.isAfter( last.end ) ) {
  220. last = range;
  221. }
  222. }
  223. return last ? Range.createFromRange( last ) : null;
  224. }
  225. /**
  226. * Returns copy of the first position in the selection. First position is the position that
  227. * {@link module:engine/view/position~Position#isBefore is before} any other position in the selection ranges.
  228. * Returns `null` if no ranges are added to selection.
  229. *
  230. * @returns {module:engine/view/position~Position|null}
  231. */
  232. getFirstPosition() {
  233. const firstRange = this.getFirstRange();
  234. return firstRange ? Position.createFromPosition( firstRange.start ) : null;
  235. }
  236. /**
  237. * Returns copy of the last position in the selection. Last position is the position that
  238. * {@link module:engine/view/position~Position#isAfter is after} any other position in the selection ranges.
  239. * Returns `null` if no ranges are added to selection.
  240. *
  241. * @returns {module:engine/view/position~Position|null}
  242. */
  243. getLastPosition() {
  244. const lastRange = this.getLastRange();
  245. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  246. }
  247. /**
  248. * Checks whether, this selection is equal to given selection. Selections are equal if they have same directions,
  249. * same number of ranges and all ranges from one selection equal to a range from other selection.
  250. *
  251. * @param {module:engine/view/selection~Selection} otherSelection Selection to compare with.
  252. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  253. */
  254. isEqual( otherSelection ) {
  255. if ( this.isFake != otherSelection.isFake ) {
  256. return false;
  257. }
  258. if ( this.isFake && this.fakeSelectionLabel != otherSelection.fakeSelectionLabel ) {
  259. return false;
  260. }
  261. if ( this.rangeCount != otherSelection.rangeCount ) {
  262. return false;
  263. } else if ( this.rangeCount === 0 ) {
  264. return true;
  265. }
  266. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  267. return false;
  268. }
  269. for ( const thisRange of this._ranges ) {
  270. let found = false;
  271. for ( const otherRange of otherSelection._ranges ) {
  272. if ( thisRange.isEqual( otherRange ) ) {
  273. found = true;
  274. break;
  275. }
  276. }
  277. if ( !found ) {
  278. return false;
  279. }
  280. }
  281. return true;
  282. }
  283. /**
  284. * Checks whether this selection is similar to given selection. Selections are similar if they have same directions, same
  285. * number of ranges, and all {@link module:engine/view/range~Range#getTrimmed trimmed} ranges from one selection are
  286. * equal to any trimmed range from other selection.
  287. *
  288. * @param {module:engine/view/selection~Selection} otherSelection Selection to compare with.
  289. * @returns {Boolean} `true` if selections are similar, `false` otherwise.
  290. */
  291. isSimilar( otherSelection ) {
  292. if ( this.isBackward != otherSelection.isBackward ) {
  293. return false;
  294. }
  295. const numOfRangesA = count( this.getRanges() );
  296. const numOfRangesB = count( otherSelection.getRanges() );
  297. // If selections have different number of ranges, they cannot be similar.
  298. if ( numOfRangesA != numOfRangesB ) {
  299. return false;
  300. }
  301. // If both selections have no ranges, they are similar.
  302. if ( numOfRangesA == 0 ) {
  303. return true;
  304. }
  305. // Check if each range in one selection has a similar range in other selection.
  306. for ( let rangeA of this.getRanges() ) {
  307. rangeA = rangeA.getTrimmed();
  308. let found = false;
  309. for ( let rangeB of otherSelection.getRanges() ) {
  310. rangeB = rangeB.getTrimmed();
  311. if ( rangeA.start.isEqual( rangeB.start ) && rangeA.end.isEqual( rangeB.end ) ) {
  312. found = true;
  313. break;
  314. }
  315. }
  316. // For `rangeA`, neither range in `otherSelection` was similar. So selections are not similar.
  317. if ( !found ) {
  318. return false;
  319. }
  320. }
  321. // There were no ranges that weren't matched. Selections are similar.
  322. return true;
  323. }
  324. /**
  325. * Returns the selected element. {@link module:engine/view/element~Element Element} is considered as selected if there is only
  326. * one range in the selection, and that range contains exactly one element.
  327. * Returns `null` if there is no selected element.
  328. *
  329. * @returns {module:engine/view/element~Element|null}
  330. */
  331. getSelectedElement() {
  332. if ( this.rangeCount !== 1 ) {
  333. return null;
  334. }
  335. const range = this.getFirstRange();
  336. const nodeAfterStart = range.start.nodeAfter;
  337. const nodeBeforeEnd = range.end.nodeBefore;
  338. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  339. }
  340. /**
  341. * Removes all ranges that were added to the selection.
  342. *
  343. * @fires change
  344. */
  345. _removeAllRanges() {
  346. if ( this._ranges.length ) {
  347. this._ranges = [];
  348. this.fire( 'change' );
  349. }
  350. }
  351. /**
  352. * Sets this selection's ranges and direction to the specified location based on the given
  353. * {@link module:engine/view/selection~Selection selection}, {@link module:engine/view/position~Position position},
  354. * {@link module:engine/view/item~Item item}, {@link module:engine/view/range~Range range},
  355. * an iterable of {@link module:engine/view/range~Range ranges} or null.
  356. *
  357. * // Sets ranges from the given range.
  358. * const range = new Range( start, end );
  359. * selection.setTo( range, isBackwardSelection );
  360. *
  361. * // Sets ranges from the iterable of ranges.
  362. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  363. * selection.setTo( range, isBackwardSelection );
  364. *
  365. * // Sets ranges from the other selection.
  366. * const otherSelection = new Selection();
  367. * selection.setTo( otherSelection );
  368. *
  369. * // Sets collapsed range at the given position.
  370. * const position = new Position( root, path );
  371. * selection.setTo( position );
  372. *
  373. * // Sets collapsed range on the given item.
  374. * const paragraph = writer.createElement( 'paragraph' );
  375. * selection.setTo( paragraph, offset );
  376. *
  377. * // Removes all ranges.
  378. * selection.setTo( null );
  379. *
  380. * @protected
  381. * @param {module:engine/view/selection~Selection|module:engine/view/position~Position|
  382. * Iterable.<module:engine/view/range~Range>|module:engine/view/range~Range|module:engine/view/item~Item|null} selectable
  383. * @param {Boolean|Number|'before'|'end'|'after'} [backwardSelectionOrOffset]
  384. */
  385. _setTo( selectable, backwardSelectionOrOffset ) {
  386. if ( selectable === null ) {
  387. this._removeAllRanges();
  388. } else if ( selectable instanceof Selection ) {
  389. this._isFake = selectable.isFake;
  390. this._fakeSelectionLabel = selectable.fakeSelectionLabel;
  391. this._setRanges( selectable.getRanges(), selectable.isBackward );
  392. } else if ( selectable instanceof Range ) {
  393. this._setRanges( [ selectable ], backwardSelectionOrOffset );
  394. } else if ( selectable instanceof Position ) {
  395. this._setRanges( [ new Range( selectable ) ] );
  396. } else if ( selectable instanceof Text ) {
  397. this._setRanges( [ Range.createCollapsedAt( selectable, backwardSelectionOrOffset ) ] );
  398. } else if ( selectable instanceof Element ) {
  399. this._setRanges( [ Range.createCollapsedAt( selectable, backwardSelectionOrOffset ) ] );
  400. } else if ( isIterable( selectable ) ) {
  401. // We assume that the selectable is an iterable of ranges.
  402. this._setRanges( selectable, backwardSelectionOrOffset );
  403. } else {
  404. /**
  405. * Cannot set selection to given place.
  406. *
  407. * @error view-selection-setTo-not-selectable
  408. */
  409. throw new CKEditorError( 'view-selection-setTo-not-selectable: Cannot set selection to given place.' );
  410. }
  411. }
  412. /**
  413. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  414. * is treated like the last added range and is used to set {@link #anchor anchor} and {@link #focus focus}.
  415. * Accepts a flag describing in which way the selection is made.
  416. *
  417. * @protected
  418. * @fires change
  419. * @param {Iterable.<module:engine/view/range~Range>} newRanges Iterable object of ranges to set.
  420. * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end
  421. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  422. */
  423. _setRanges( newRanges, isLastBackward ) {
  424. this._ranges = [];
  425. for ( const range of newRanges ) {
  426. this._addRange( range );
  427. }
  428. this._lastRangeBackward = !!isLastBackward;
  429. this.fire( 'change' );
  430. }
  431. /**
  432. * Moves {@link #focus} to the specified location.
  433. *
  434. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  435. *
  436. * @protected
  437. * @fires change
  438. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  439. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  440. * first parameter is a {@link module:engine/view/item~Item view item}.
  441. */
  442. _setFocus( itemOrPosition, offset ) {
  443. if ( this.anchor === null ) {
  444. /**
  445. * Cannot set selection focus if there are no ranges in selection.
  446. *
  447. * @error view-selection-setFocus-no-ranges
  448. */
  449. throw new CKEditorError(
  450. 'view-selection-setFocus-no-ranges: Cannot set selection focus if there are no ranges in selection.'
  451. );
  452. }
  453. const newFocus = Position.createAt( itemOrPosition, offset );
  454. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  455. return;
  456. }
  457. const anchor = this.anchor;
  458. this._ranges.pop();
  459. if ( newFocus.compareWith( anchor ) == 'before' ) {
  460. this._addRange( new Range( newFocus, anchor ), true );
  461. } else {
  462. this._addRange( new Range( anchor, newFocus ) );
  463. }
  464. this.fire( 'change' );
  465. }
  466. /**
  467. * Sets this selection instance to be marked as `fake`. A fake selection does not render as browser native selection
  468. * over selected elements and is hidden to the user. This way, no native selection UI artifacts are displayed to
  469. * the user and selection over elements can be represented in other way, for example by applying proper CSS class.
  470. *
  471. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
  472. * properly handled by screen readers).
  473. *
  474. * @protected
  475. * @fires change
  476. * @param {Boolean} [value=true] If set to true selection will be marked as `fake`.
  477. * @param {Object} [options] Additional options.
  478. * @param {String} [options.label=''] Fake selection label.
  479. */
  480. _setFake( value = true, options = {} ) {
  481. this._isFake = value;
  482. this._fakeSelectionLabel = value ? options.label || '' : '';
  483. this.fire( 'change' );
  484. }
  485. /**
  486. * Adds a range to the selection. Added range is copied. This means that passed range is not saved in the
  487. * selection instance and you can safely operate on it.
  488. *
  489. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  490. * {@link module:engine/view/range~Range#start start} to {@link module:engine/view/range~Range#end end}
  491. * or from {@link module:engine/view/range~Range#end end} to {@link module:engine/view/range~Range#start start}.
  492. * The flag is used to set {@link #anchor anchor} and {@link #focus focus} properties.
  493. *
  494. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  495. * with ranges already stored in Selection instance.
  496. *
  497. * @private
  498. * @fires change
  499. * @param {module:engine/view/range~Range} range
  500. * @param {Boolean} [isBackward]
  501. */
  502. _addRange( range, isBackward = false ) {
  503. if ( !( range instanceof Range ) ) {
  504. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  505. }
  506. this._pushRange( range );
  507. this._lastRangeBackward = !!isBackward;
  508. }
  509. /**
  510. * Adds range to selection - creates copy of given range so it can be safely used and modified.
  511. *
  512. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  513. * with ranges already stored in selection instance.
  514. *
  515. * @private
  516. * @param {module:engine/view/range~Range} range
  517. */
  518. _pushRange( range ) {
  519. for ( const storedRange of this._ranges ) {
  520. if ( range.isIntersecting( storedRange ) ) {
  521. /**
  522. * Trying to add a range that intersects with another range from selection.
  523. *
  524. * @error view-selection-range-intersects
  525. * @param {module:engine/view/range~Range} addedRange Range that was added to the selection.
  526. * @param {module:engine/view/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  527. */
  528. throw new CKEditorError(
  529. 'view-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  530. { addedRange: range, intersectingRange: storedRange }
  531. );
  532. }
  533. }
  534. this._ranges.push( Range.createFromRange( range ) );
  535. }
  536. }
  537. mix( Selection, EmitterMixin );
  538. /**
  539. * Fired whenever selection ranges are changed through {@link ~Selection Selection API}.
  540. *
  541. * @event change
  542. */