selection.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. /**
  47. * Selection anchor. Anchor may be described as a position where the selection starts. Together with
  48. * {@link engine.view.Selection#focus focus} they define the direction of selection, which is important
  49. * when expanding/shrinking selection. Anchor is always the start or end of the most recent added range.
  50. * It may be a bit unintuitive when there are multiple ranges in selection.
  51. *
  52. * @see engine.view.Selection#focus
  53. * @type {engine.view.Position}
  54. */
  55. get anchor() {
  56. if ( !this._ranges.length ) {
  57. return null;
  58. }
  59. const range = this._ranges[ this._ranges.length - 1 ];
  60. const anchor = this._lastRangeBackward ? range.end : range.start;
  61. return Position.createFromPosition( anchor );
  62. }
  63. /**
  64. * Selection focus. Focus is a position where the selection ends.
  65. *
  66. * @see engine.view.Selection#anchor
  67. * @type {engine.view.Position}
  68. */
  69. get focus() {
  70. if ( !this._ranges.length ) {
  71. return null;
  72. }
  73. const range = this._ranges[ this._ranges.length - 1 ];
  74. const focus = this._lastRangeBackward ? range.start : range.end;
  75. return Position.createFromPosition( focus );
  76. }
  77. /**
  78. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  79. * collapsed.
  80. *
  81. * @type {Boolean}
  82. */
  83. get isCollapsed() {
  84. return this.rangeCount === 1 && this._ranges[ 0 ].isCollapsed;
  85. }
  86. /**
  87. * Returns number of ranges in selection.
  88. *
  89. * @type {Number}
  90. */
  91. get rangeCount() {
  92. return this._ranges.length;
  93. }
  94. /**
  95. * Specifies whether the {@link engine.view.Selection#focus} precedes {@link engine.view.Selection#anchor}.
  96. *
  97. * @type {Boolean}
  98. */
  99. get isBackward() {
  100. return !this.isCollapsed && this._lastRangeBackward;
  101. }
  102. /**
  103. * {@link engine.view.EditableElement EditableElement} instance that contains this selection, or `null`
  104. * if the selection is not inside an editable element.
  105. *
  106. * @type {engine.view.EditableElement|null}
  107. */
  108. get editableElement() {
  109. if ( this.anchor ) {
  110. return this.anchor.editableElement;
  111. }
  112. return null;
  113. }
  114. /**
  115. * Adds a range to the selection. Added range is copied. This means that passed range is not saved in the
  116. * selection instance and you can safely operate on it.
  117. *
  118. * Accepts a flag describing in which way the selection is made - passed range might be selected from
  119. * {@link engine.view.Range#start start} to {@link engine.view.Range#end end}
  120. * or from {@link engine.view.Range#end end} to {@link engine.view.Range#start start}.
  121. * The flag is used to set {@link engine.view.Selection#anchor anchor} and
  122. * {@link engine.view.Selection#focus focus} properties.
  123. *
  124. * Throws {@link utils.CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  125. * with ranges already stored in Selection instance.
  126. *
  127. * @fires engine.view.Selection#change
  128. * @param {engine.view.Range} range
  129. */
  130. addRange( range, isBackward ) {
  131. if ( !( range instanceof Range ) ) {
  132. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  133. }
  134. this._pushRange( range );
  135. this._lastRangeBackward = !!isBackward;
  136. this.fire( 'change' );
  137. }
  138. /**
  139. * Returns an iterator that contains copies of all ranges added to the selection.
  140. *
  141. * @returns {Iterator.<engine.view.Range>}
  142. */
  143. *getRanges() {
  144. for ( let range of this._ranges ) {
  145. yield Range.createFromRange( range );
  146. }
  147. }
  148. /**
  149. * Returns copy of the first range in the selection. First range is the one which
  150. * {@link engine.view.Range#start start} position {@link engine.view.Position#isBefore is before} start
  151. * position of all other ranges (not to confuse with the first range added to the selection).
  152. * Returns `null` if no ranges are added to selection.
  153. *
  154. * @returns {engine.view.Range|null}
  155. */
  156. getFirstRange() {
  157. let first = null;
  158. for ( let range of this._ranges ) {
  159. if ( !first || range.start.isBefore( first.start ) ) {
  160. first = range;
  161. }
  162. }
  163. return first ? Range.createFromRange( first ) : null;
  164. }
  165. /**
  166. * Returns copy of the last range in the selection. Last range is the one which {@link engine.view.Range#end end}
  167. * position {@link engine.view.Position#isAfter is after} end position of all other ranges (not to confuse
  168. * with the last range added to the selection). Returns `null` if no ranges are added to selection.
  169. *
  170. * @returns {engine.view.Range|null}
  171. */
  172. getLastRange() {
  173. let last = null;
  174. for ( let range of this._ranges ) {
  175. if ( !last || range.end.isAfter( last.end ) ) {
  176. last = range;
  177. }
  178. }
  179. return last ? Range.createFromRange( last ) : null;
  180. }
  181. /**
  182. * Returns copy of the first position in the selection. First position is the position that
  183. * {@link engine.view.Position#isBefore is before} any other position in the selection ranges.
  184. * Returns `null` if no ranges are added to selection.
  185. *
  186. * @returns {engine.view.Position|null}
  187. */
  188. getFirstPosition() {
  189. const firstRange = this.getFirstRange();
  190. return firstRange ? Position.createFromPosition( firstRange.start ) : null;
  191. }
  192. /**
  193. * Returns copy of the last position in the selection. Last position is the position that
  194. * {@link engine.view.Position#isAfter is after} any other position in the selection ranges.
  195. * Returns `null` if no ranges are added to selection.
  196. *
  197. * @returns {engine.view.Position|null}
  198. */
  199. getLastPosition() {
  200. const lastRange = this.getLastRange();
  201. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  202. }
  203. /**
  204. * Checks whether, this selection is equal to given selection. Selections equal if they have the same ranges and directions.
  205. *
  206. * @param {engine.view.Selection} otherSelection Selection to compare with.
  207. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  208. */
  209. isEqual( otherSelection ) {
  210. const rangeCount = this.rangeCount;
  211. if ( rangeCount != otherSelection.rangeCount ) {
  212. return false;
  213. }
  214. for ( let i = 0; i < this.rangeCount; i++ ) {
  215. if ( !this._ranges[ i ].isEqual( otherSelection._ranges[ i ] ) ) {
  216. return false;
  217. }
  218. }
  219. return this._lastRangeBackward === otherSelection._lastRangeBackward;
  220. }
  221. /**
  222. * Removes all ranges that were added to the selection.
  223. *
  224. * @fires engine.view.Selection#change
  225. */
  226. removeAllRanges() {
  227. if ( this._ranges.length ) {
  228. this._ranges = [];
  229. this.fire( 'change' );
  230. }
  231. }
  232. /**
  233. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  234. * is treated like the last added range and is used to set {@link engine.view.Selection#anchor anchor} and
  235. * {@link engine.view.Selection#focus focus}. Accepts a flag describing in which way the selection is made
  236. * (see {@link engine.view.Selection#addRange addRange}).
  237. *
  238. * @fires engine.view.Selection#change
  239. * @param {Array.<engine.view.Range>} newRanges Array of ranges to set.
  240. * @param {Boolean} [isLastBackward] Flag describing if last added range was selected forward - from start to end
  241. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  242. */
  243. setRanges( newRanges, isLastBackward ) {
  244. this._ranges = [];
  245. for ( let range of newRanges ) {
  246. if ( !( range instanceof Range ) ) {
  247. throw new CKEditorError( 'view-selection-invalid-range: Invalid Range.' );
  248. }
  249. this._pushRange( range );
  250. }
  251. this._lastRangeBackward = !!isLastBackward;
  252. this.fire( 'change' );
  253. }
  254. /**
  255. * Sets this selection's ranges and direction to the ranges and direction of the given selection.
  256. *
  257. * @param {engine.view.Selection} otherSelection
  258. */
  259. setTo( otherSelection ) {
  260. this.setRanges( otherSelection.getRanges(), otherSelection.isBackward );
  261. }
  262. /**
  263. * Sets collapsed selection in the specified location.
  264. *
  265. * The location can be specified in the same form as {@link engine.view.Position.createAt} parameters.
  266. *
  267. * @fires engine.view.Selection#change
  268. * @param {engine.view.Item|engine.view.Position} itemOrPosition
  269. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  270. * first parameter is a {@link engine.view.Item view item}.
  271. */
  272. collapse( itemOrPosition, offset ) {
  273. const pos = Position.createAt( itemOrPosition, offset );
  274. const range = new Range( pos, pos );
  275. this.setRanges( [ range ] );
  276. }
  277. /**
  278. * Collapses selection to the selection's {@link engine.view.Selection#getFirstPosition first position}.
  279. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  280. * inside selection.
  281. *
  282. * @fires engine.view.Selection#change
  283. */
  284. collapseToStart() {
  285. const startPosition = this.getFirstPosition();
  286. if ( startPosition !== null ) {
  287. this.setRanges( [ new Range( startPosition, startPosition ) ] );
  288. }
  289. }
  290. /**
  291. * Collapses selection to the selection's {@link engine.view.Selection#getLastPosition last position}.
  292. * All ranges, besides the collapsed one, will be removed. Nothing will change if there are no ranges stored
  293. * inside selection.
  294. *
  295. * @fires engine.view.Selection#change
  296. */
  297. collapseToEnd() {
  298. const endPosition = this.getLastPosition();
  299. if ( endPosition !== null ) {
  300. this.setRanges( [ new Range( endPosition, endPosition ) ] );
  301. }
  302. }
  303. /**
  304. * Creates and returns an instance of `Selection` that is a clone of given selection, meaning that it has same
  305. * ranges and same direction as this selection.
  306. *
  307. * @params {engine.view.Selection} otherSelection Selection to be cloned.
  308. * @returns {engine.view.Selection} `Selection` instance that is a clone of given selection.
  309. */
  310. static createFromSelection( otherSelection ) {
  311. const selection = new Selection();
  312. selection.setTo( otherSelection );
  313. return selection;
  314. }
  315. /**
  316. * Adds range to selection - creates copy of given range so it can be safely used and modified.
  317. *
  318. * Throws {@link utils.CKEditorError CKEditorError} `view-selection-range-intersects` if added range intersects
  319. * with ranges already stored in selection instance.
  320. *
  321. * @private
  322. * @param {engine.view.Range} range
  323. */
  324. _pushRange( range ) {
  325. for ( let storedRange of this._ranges ) {
  326. if ( range.isIntersecting( storedRange ) ) {
  327. /**
  328. * Trying to add a range that intersects with another range from selection.
  329. *
  330. * @error selection-range-intersects
  331. * @param {engine.view.Range} addedRange Range that was added to the selection.
  332. * @param {engine.view.Range} intersectingRange Range from selection that intersects with `addedRange`.
  333. */
  334. throw new CKEditorError(
  335. 'view-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  336. { addedRange: range, intersectingRange: storedRange }
  337. );
  338. }
  339. }
  340. this._ranges.push( Range.createFromRange( range ) );
  341. }
  342. }
  343. mix( Selection, EmitterMixin );
  344. /**
  345. * Fired whenever selection ranges are changed through {@link engine.view.Selection Selection API}.
  346. *
  347. * @event engine.view.Selection#change
  348. */