8
0

selection.js 19 KB

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