selection.js 16 KB

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