selection.js 19 KB

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