documentselection.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/documentselection
  7. */
  8. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  9. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  10. import Selection from './selection';
  11. import LiveRange from './liverange';
  12. import Text from './text';
  13. import TextProxy from './textproxy';
  14. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  15. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  16. import log from '@ckeditor/ckeditor5-utils/src/log';
  17. import uid from '@ckeditor/ckeditor5-utils/src/uid';
  18. const storePrefix = 'selection:';
  19. /**
  20. * `DocumentSelection` is a special selection which is used as the
  21. * {@link module:engine/model/document~Document#selection document's selection}.
  22. * There can be only one instance of `DocumentSelection` per document.
  23. *
  24. * Document selection can only be changed by using the {@link module:engine/model/writer~Writer} instance
  25. * inside the {@link module:engine/model/model~Model#change `change()`} block, as it provides a secure way to modify model.
  26. *
  27. * `DocumentSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
  28. * to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
  29. *
  30. * Differences between {@link module:engine/model/selection~Selection} and `DocumentSelection` are:
  31. * * there is always a range in `DocumentSelection` - even if no ranges were added there is a "default range"
  32. * present in the selection,
  33. * * ranges added to this selection updates automatically when the document changes,
  34. * * attributes of `DocumentSelection` are updated automatically according to selection ranges.
  35. *
  36. * Since `DocumentSelection` uses {@link module:engine/model/liverange~LiveRange live ranges}
  37. * and is updated when {@link module:engine/model/document~Document document}
  38. * changes, it cannot be set on {@link module:engine/model/node~Node nodes}
  39. * that are inside {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
  40. * If you need to represent a selection in document fragment,
  41. * use {@link module:engine/model/selection~Selection Selection class} instead.
  42. *
  43. * @mixes module:utils/emittermixin~EmitterMixin
  44. */
  45. export default class DocumentSelection {
  46. /**
  47. * Creates an empty live selection for given {@link module:engine/model/document~Document}.
  48. *
  49. * @param {module:engine/model/document~Document} doc Document which owns this selection.
  50. */
  51. constructor( doc ) {
  52. /**
  53. * Selection used internally by that class (`DocumentSelection` is a proxy to that selection).
  54. *
  55. * @protected
  56. */
  57. this._selection = new LiveSelection( doc );
  58. this._selection.delegate( 'change:range' ).to( this );
  59. this._selection.delegate( 'change:attribute' ).to( this );
  60. }
  61. /**
  62. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  63. * collapsed.
  64. *
  65. * @readonly
  66. * @type {Boolean}
  67. */
  68. get isCollapsed() {
  69. return this._selection.isCollapsed;
  70. }
  71. /**
  72. * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
  73. * Together with {@link #focus} they define the direction of selection, which is important
  74. * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
  75. * {@link module:engine/model/range~Range#end end} position of the most recently added range.
  76. *
  77. * Is set to `null` if there are no ranges in selection.
  78. *
  79. * @see #focus
  80. * @readonly
  81. * @type {module:engine/model/position~Position|null}
  82. */
  83. get anchor() {
  84. return this._selection.anchor;
  85. }
  86. /**
  87. * Selection focus. Focus is a position where the selection ends.
  88. *
  89. * Is set to `null` if there are no ranges in selection.
  90. *
  91. * @see #anchor
  92. * @readonly
  93. * @type {module:engine/model/position~Position|null}
  94. */
  95. get focus() {
  96. return this._selection.focus;
  97. }
  98. /**
  99. * Returns number of ranges in selection.
  100. *
  101. * @readonly
  102. * @type {Number}
  103. */
  104. get rangeCount() {
  105. return this._selection.rangeCount;
  106. }
  107. /**
  108. * Describes whether `Documentselection` has own range(s) set, or if it is defaulted to
  109. * {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
  110. *
  111. * @readonly
  112. * @type {Boolean}
  113. */
  114. get hasOwnRange() {
  115. return this._selection.hasOwnRange;
  116. }
  117. /**
  118. * Specifies whether the {@link #focus}
  119. * precedes {@link #anchor}.
  120. *
  121. * @readonly
  122. * @type {Boolean}
  123. */
  124. get isBackward() {
  125. return this._selection.isBackward;
  126. }
  127. /**
  128. * Describes whether the gravity is overridden (using {@link module:engine/model/writer~Writer#overrideSelectionGravity}) or not.
  129. *
  130. * Note that the gravity remains overridden as long as will not be restored the same number of times as it was overridden.
  131. *
  132. * @readonly
  133. * @returns {Boolean}
  134. */
  135. get isGravityOverridden() {
  136. return this._selection.isGravityOverridden;
  137. }
  138. /**
  139. * Used for the compatibility with the {@link module:engine/model/selection~Selection#isEqual} method.
  140. *
  141. * @protected
  142. */
  143. get _ranges() {
  144. return this._selection._ranges;
  145. }
  146. /**
  147. * Returns an iterable that iterates over copies of selection ranges.
  148. *
  149. * @returns {Iterable.<module:engine/model/range~Range>}
  150. */
  151. getRanges() {
  152. return this._selection.getRanges();
  153. }
  154. /**
  155. * Returns the first position in the selection.
  156. * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
  157. * any other position in the selection.
  158. *
  159. * Returns `null` if there are no ranges in selection.
  160. *
  161. * @returns {module:engine/model/position~Position|null}
  162. */
  163. getFirstPosition() {
  164. return this._selection.getFirstPosition();
  165. }
  166. /**
  167. * Returns the last position in the selection.
  168. * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
  169. * any other position in the selection.
  170. *
  171. * Returns `null` if there are no ranges in selection.
  172. *
  173. * @returns {module:engine/model/position~Position|null}
  174. */
  175. getLastPosition() {
  176. return this._selection.getLastPosition();
  177. }
  178. /**
  179. * Returns a copy of the first range in the selection.
  180. * First range is the one which {@link module:engine/model/range~Range#start start} position
  181. * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
  182. * (not to confuse with the first range added to the selection).
  183. *
  184. * Returns `null` if there are no ranges in selection.
  185. *
  186. * @returns {module:engine/model/range~Range|null}
  187. */
  188. getFirstRange() {
  189. return this._selection.getFirstRange();
  190. }
  191. /**
  192. * Returns a copy of the last range in the selection.
  193. * Last range is the one which {@link module:engine/model/range~Range#end end} position
  194. * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
  195. * recently added to the selection).
  196. *
  197. * Returns `null` if there are no ranges in selection.
  198. *
  199. * @returns {module:engine/model/range~Range|null}
  200. */
  201. getLastRange() {
  202. return this._selection.getLastRange();
  203. }
  204. /**
  205. * Gets elements of type "block" touched by the selection.
  206. *
  207. * This method's result can be used for example to apply block styling to all blocks covered by this selection.
  208. *
  209. * **Note:** `getSelectedBlocks()` always returns the deepest block.
  210. *
  211. * In this case the function will return exactly all 3 paragraphs:
  212. *
  213. * <paragraph>[a</paragraph>
  214. * <quote>
  215. * <paragraph>b</paragraph>
  216. * </quote>
  217. * <paragraph>c]d</paragraph>
  218. *
  219. * In this case the paragraph will also be returned, despite the collapsed selection:
  220. *
  221. * <paragraph>[]a</paragraph>
  222. *
  223. * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
  224. * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
  225. *
  226. * <paragraph>[a</paragraph>
  227. * <paragraph>b</paragraph>
  228. * <paragraph>]c</paragraph> // this block will not be returned
  229. *
  230. * @returns {Iterator.<module:engine/model/element~Element>}
  231. */
  232. getSelectedBlocks() {
  233. return this._selection.getSelectedBlocks();
  234. }
  235. /**
  236. * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
  237. * one range in the selection, and that range contains exactly one element.
  238. * Returns `null` if there is no selected element.
  239. *
  240. * @returns {module:engine/model/element~Element|null}
  241. */
  242. getSelectedElement() {
  243. return this._selection.getSelectedElement();
  244. }
  245. /**
  246. * Checks whether the selection contains the entire content of the given element. This means that selection must start
  247. * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
  248. * touching the element's end.
  249. *
  250. * By default, this method will check whether the entire content of the selection's current root is selected.
  251. * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
  252. *
  253. * @param {module:engine/model/element~Element} [element=this.anchor.root]
  254. * @returns {Boolean}
  255. */
  256. containsEntireContent( element ) {
  257. return this._selection.containsEntireContent( element );
  258. }
  259. /**
  260. * Unbinds all events previously bound by document selection.
  261. */
  262. destroy() {
  263. this._selection.destroy();
  264. }
  265. /**
  266. * Returns iterable that iterates over this selection's attribute keys.
  267. *
  268. * @returns {Iterable.<String>}
  269. */
  270. getAttributeKeys() {
  271. return this._selection.getAttributeKeys();
  272. }
  273. /**
  274. * Returns iterable that iterates over this selection's attributes.
  275. *
  276. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  277. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  278. *
  279. * @returns {Iterable.<*>}
  280. */
  281. getAttributes() {
  282. return this._selection.getAttributes();
  283. }
  284. /**
  285. * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
  286. *
  287. * @param {String} key Key of attribute to look for.
  288. * @returns {*} Attribute value or `undefined`.
  289. */
  290. getAttribute( key ) {
  291. return this._selection.getAttribute( key );
  292. }
  293. /**
  294. * Checks if the selection has an attribute for given key.
  295. *
  296. * @param {String} key Key of attribute to check.
  297. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  298. */
  299. hasAttribute( key ) {
  300. return this._selection.hasAttribute( key );
  301. }
  302. /**
  303. * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
  304. * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionFocus} method.
  305. *
  306. * The location can be specified in the same form as
  307. * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
  308. *
  309. * @see module:engine/model/writer~Writer#setSelectionFocus
  310. * @protected
  311. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  312. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  313. * first parameter is a {@link module:engine/model/item~Item model item}.
  314. */
  315. _setFocus( itemOrPosition, offset ) {
  316. this._selection.setFocus( itemOrPosition, offset );
  317. }
  318. /**
  319. * Sets this selection's ranges and direction to the specified location based on the given
  320. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  321. * {@link module:engine/model/node~Node node}, {@link module:engine/model/position~Position position},
  322. * {@link module:engine/model/range~Range range}, an iterable of {@link module:engine/model/range~Range ranges} or null.
  323. * Should be used only within the {@link module:engine/model/writer~Writer#setSelection} method.
  324. *
  325. * @see module:engine/model/writer~Writer#setSelection
  326. * @protected
  327. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  328. * module:engine/model/position~Position|module:engine/model/node~Node|
  329. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range|null} selectable
  330. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  331. * @param {Object} [options]
  332. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  333. */
  334. _setTo( selectable, placeOrOffset, options ) {
  335. this._selection.setTo( selectable, placeOrOffset, options );
  336. }
  337. /**
  338. * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
  339. * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionAttribute} method.
  340. *
  341. * @see module:engine/model/writer~Writer#setSelectionAttribute
  342. * @protected
  343. * @param {String} key Key of the attribute to set.
  344. * @param {*} value Attribute value.
  345. */
  346. _setAttribute( key, value ) {
  347. this._selection.setAttribute( key, value );
  348. }
  349. /**
  350. * Removes an attribute with given key from the selection.
  351. * If the given attribute was set on the selection, fires the {@link module:engine/model/selection~Selection#event:change:range}
  352. * event with removed attribute key.
  353. * Should be used only within the {@link module:engine/model/writer~Writer#removeSelectionAttribute} method.
  354. *
  355. * @see module:engine/model/writer~Writer#removeSelectionAttribute
  356. * @protected
  357. * @param {String} key Key of the attribute to remove.
  358. */
  359. _removeAttribute( key ) {
  360. this._selection.removeAttribute( key );
  361. }
  362. /**
  363. * Returns an iterable that iterates through all selection attributes stored in current selection's parent.
  364. *
  365. * @protected
  366. * @returns {Iterable.<*>}
  367. */
  368. _getStoredAttributes() {
  369. return this._selection._getStoredAttributes();
  370. }
  371. /**
  372. * Temporarily changes the gravity of the selection from the left to the right.
  373. *
  374. * The gravity defines from which direction the selection inherits its attributes. If it's the default left
  375. * gravity, the selection (after being moved by the the user) inherits attributes from its left hand side.
  376. * This method allows to temporarily override this behavior by forcing the gravity to the right.
  377. *
  378. * It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
  379. * of the process.
  380. *
  381. * @see module:engine/model/writer~Writer#overrideSelectionGravity
  382. * @protected
  383. * @returns {String} The unique id which allows restoring the gravity.
  384. */
  385. _overrideGravity() {
  386. return this._selection.overrideGravity();
  387. }
  388. /**
  389. * Restores the {@link ~DocumentSelection#_overrideGravity overridden gravity}.
  390. *
  391. * Restoring the gravity is only possible using the unique identifier returned by
  392. * {@link ~DocumentSelection#_overrideGravity}. Note that the gravity remains overridden as long as won't be restored
  393. * the same number of times it was overridden.
  394. *
  395. * @see module:engine/model/writer~Writer#restoreSelectionGravity
  396. * @protected
  397. * @param {String} uid The unique id returned by {@link #_overrideGravity}.
  398. */
  399. _restoreGravity( uid ) {
  400. this._selection.restoreGravity( uid );
  401. }
  402. /**
  403. * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
  404. *
  405. * @protected
  406. * @param {String} key Attribute key to convert.
  407. * @returns {String} Converted attribute key, applicable for selection store.
  408. */
  409. static _getStoreAttributeKey( key ) {
  410. return storePrefix + key;
  411. }
  412. /**
  413. * Checks whether the given attribute key is an attribute stored on an element.
  414. *
  415. * @protected
  416. * @param {String} key
  417. * @returns {Boolean}
  418. */
  419. static _isStoreAttributeKey( key ) {
  420. return key.startsWith( storePrefix );
  421. }
  422. }
  423. mix( DocumentSelection, EmitterMixin );
  424. /**
  425. * Fired when selection range(s) changed.
  426. *
  427. * @event change:range
  428. * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
  429. * to `true` which indicates that the selection change was caused by a direct use of selection's API.
  430. * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its position
  431. * was directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
  432. * changed because the structure of the model has been changed (which means an indirect change).
  433. * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
  434. * which mean that they are not updated once the document changes.
  435. */
  436. /**
  437. * Fired when selection attribute changed.
  438. *
  439. * @event change:attribute
  440. * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
  441. * to `true` which indicates that the selection change was caused by a direct use of selection's API.
  442. * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its attributes
  443. * were directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
  444. * changed in the model and its attributes were refreshed (which means an indirect change).
  445. * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
  446. * which mean that they are not updated once the document changes.
  447. * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
  448. */
  449. // `LiveSelection` is used internally by {@link module:engine/model/documentselection~DocumentSelection} and shouldn't be used directly.
  450. //
  451. // LiveSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
  452. // to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
  453. //
  454. // Differences between {@link module:engine/model/selection~Selection} and `LiveSelection` are:
  455. // * there is always a range in `LiveSelection` - even if no ranges were added there is a "default range"
  456. // present in the selection,
  457. // * ranges added to this selection updates automatically when the document changes,
  458. // * attributes of `LiveSelection` are updated automatically according to selection ranges.
  459. //
  460. // @extends module:engine/model/selection~Selection
  461. //
  462. class LiveSelection extends Selection {
  463. // Creates an empty live selection for given {@link module:engine/model/document~Document}.
  464. // @param {module:engine/model/document~Document} doc Document which owns this selection.
  465. constructor( doc ) {
  466. super();
  467. // Document which owns this selection.
  468. //
  469. // @protected
  470. // @member {module:engine/model/model~Model}
  471. this._model = doc.model;
  472. // Document which owns this selection.
  473. //
  474. // @protected
  475. // @member {module:engine/model/document~Document}
  476. this._document = doc;
  477. // Keeps mapping of attribute name to priority with which the attribute got modified (added/changed/removed)
  478. // last time. Possible values of priority are: `'low'` and `'normal'`.
  479. //
  480. // Priorities are used by internal `LiveSelection` mechanisms. All attributes set using `LiveSelection`
  481. // attributes API are set with `'normal'` priority.
  482. //
  483. // @private
  484. // @member {Map} module:engine/model/liveselection~LiveSelection#_attributePriority
  485. this._attributePriority = new Map();
  486. // Contains data required to fix ranges which have been moved to the graveyard.
  487. // @private
  488. // @member {Array} module:engine/model/liveselection~LiveSelection#_fixGraveyardRangesData
  489. this._fixGraveyardRangesData = [];
  490. // Flag that informs whether the selection ranges have changed. It is changed on true when `LiveRange#change:range` event is fired.
  491. // @private
  492. // @member {Array} module:engine/model/liveselection~LiveSelection#_hasChangedRange
  493. this._hasChangedRange = false;
  494. // Each overriding gravity adds an UID to the set and each removal removes it.
  495. // Gravity is overridden when there's at least one UID in the set.
  496. // Gravity is restored when the set is empty.
  497. // This is to prevent conflicts when gravity is overridden by more than one feature at the same time.
  498. // @private
  499. // @type {Set}
  500. this._overriddenGravityRegister = new Set();
  501. // Add events that will ensure selection correctness.
  502. this.on( 'change:range', () => {
  503. for ( const range of this.getRanges() ) {
  504. if ( !this._document._validateSelectionRange( range ) ) {
  505. /**
  506. * Range from {@link module:engine/model/documentselection~DocumentSelection document selection}
  507. * starts or ends at incorrect position.
  508. *
  509. * @error document-selection-wrong-position
  510. * @param {module:engine/model/range~Range} range
  511. */
  512. throw new CKEditorError(
  513. 'document-selection-wrong-position: Range from document selection starts or ends at incorrect position.',
  514. { range }
  515. );
  516. }
  517. }
  518. } );
  519. this.listenTo( this._document, 'change', ( evt, batch ) => {
  520. // Update selection's attributes.
  521. this._updateAttributes( false );
  522. // Clear selection attributes from element if no longer empty.
  523. clearAttributesStoredInElement( this._model, batch );
  524. } );
  525. this.listenTo( this._model, 'applyOperation', () => {
  526. while ( this._fixGraveyardRangesData.length ) {
  527. const { liveRange, sourcePosition } = this._fixGraveyardRangesData.shift();
  528. this._fixGraveyardSelection( liveRange, sourcePosition );
  529. }
  530. if ( this._hasChangedRange ) {
  531. this._hasChangedRange = false;
  532. this.fire( 'change:range', { directChange: false } );
  533. }
  534. }, { priority: 'lowest' } );
  535. }
  536. get isCollapsed() {
  537. const length = this._ranges.length;
  538. return length === 0 ? this._document._getDefaultRange().isCollapsed : super.isCollapsed;
  539. }
  540. get anchor() {
  541. return super.anchor || this._document._getDefaultRange().start;
  542. }
  543. get focus() {
  544. return super.focus || this._document._getDefaultRange().end;
  545. }
  546. get rangeCount() {
  547. return this._ranges.length ? this._ranges.length : 1;
  548. }
  549. // Describes whether `LiveSelection` has own range(s) set, or if it is defaulted to
  550. // {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
  551. //
  552. // @readonly
  553. // @type {Boolean}
  554. get hasOwnRange() {
  555. return this._ranges.length > 0;
  556. }
  557. // When set to `true` then selection attributes on node before the caret won't be taken
  558. // into consideration while updating selection attributes.
  559. //
  560. // @protected
  561. // @type {Boolean}
  562. get isGravityOverridden() {
  563. return !!this._overriddenGravityRegister.size;
  564. }
  565. // Unbinds all events previously bound by live selection.
  566. destroy() {
  567. for ( let i = 0; i < this._ranges.length; i++ ) {
  568. this._ranges[ i ].detach();
  569. }
  570. this.stopListening();
  571. }
  572. * getRanges() {
  573. if ( this._ranges.length ) {
  574. yield* super.getRanges();
  575. } else {
  576. yield this._document._getDefaultRange();
  577. }
  578. }
  579. getFirstRange() {
  580. return super.getFirstRange() || this._document._getDefaultRange();
  581. }
  582. getLastRange() {
  583. return super.getLastRange() || this._document._getDefaultRange();
  584. }
  585. setTo( selectable, optionsOrPlaceOrOffset, options ) {
  586. super.setTo( selectable, optionsOrPlaceOrOffset, options );
  587. this._refreshAttributes();
  588. }
  589. setFocus( itemOrPosition, offset ) {
  590. super.setFocus( itemOrPosition, offset );
  591. this._refreshAttributes();
  592. }
  593. setAttribute( key, value ) {
  594. if ( this._setAttribute( key, value ) ) {
  595. // Fire event with exact data.
  596. const attributeKeys = [ key ];
  597. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  598. }
  599. }
  600. removeAttribute( key ) {
  601. if ( this._removeAttribute( key ) ) {
  602. // Fire event with exact data.
  603. const attributeKeys = [ key ];
  604. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  605. }
  606. }
  607. overrideGravity() {
  608. const overrideUid = uid();
  609. // Remember that another overriding has been requested. It will need to be removed
  610. // before the gravity is to be restored.
  611. this._overriddenGravityRegister.add( overrideUid );
  612. if ( this._overriddenGravityRegister.size === 1 ) {
  613. this._refreshAttributes();
  614. }
  615. return overrideUid;
  616. }
  617. restoreGravity( uid ) {
  618. if ( !this._overriddenGravityRegister.has( uid ) ) {
  619. /**
  620. * Restoring gravity for an unknown UID is not possible. Make sure you are using a correct
  621. * UID obtained from the {@link module:engine/model/writer~Writer#overrideSelectionGravity} to restore.
  622. *
  623. * @error document-selection-gravity-wrong-restore
  624. * @param {String} uid The unique identifier returned by
  625. * {@link module:engine/model/documentselection~DocumentSelection#_overrideGravity}.
  626. */
  627. throw new CKEditorError(
  628. 'document-selection-gravity-wrong-restore: Attempting to restore the selection gravity for an unknown UID.',
  629. { uid }
  630. );
  631. }
  632. this._overriddenGravityRegister.delete( uid );
  633. // Restore gravity only when all overriding have been restored.
  634. if ( !this.isGravityOverridden ) {
  635. this._refreshAttributes();
  636. }
  637. }
  638. // Removes all attributes from the selection and sets attributes according to the surrounding nodes.
  639. _refreshAttributes() {
  640. this._updateAttributes( true );
  641. }
  642. _popRange() {
  643. this._ranges.pop().detach();
  644. }
  645. _pushRange( range ) {
  646. const liveRange = this._prepareRange( range );
  647. // `undefined` is returned when given `range` is in graveyard root.
  648. if ( liveRange ) {
  649. this._ranges.push( liveRange );
  650. }
  651. }
  652. // Prepares given range to be added to selection. Checks if it is correct,
  653. // converts it to {@link module:engine/model/liverange~LiveRange LiveRange}
  654. // and sets listeners listening to the range's change event.
  655. //
  656. // @private
  657. // @param {module:engine/model/range~Range} range
  658. _prepareRange( range ) {
  659. this._checkRange( range );
  660. if ( range.root == this._document.graveyard ) {
  661. /**
  662. * Trying to add a Range that is in the graveyard root. Range rejected.
  663. *
  664. * @warning model-selection-range-in-graveyard
  665. */
  666. log.warn( 'model-selection-range-in-graveyard: Trying to add a Range that is in the graveyard root. Range rejected.' );
  667. return;
  668. }
  669. const liveRange = LiveRange.fromRange( range );
  670. liveRange.on( 'change:range', ( evt, oldRange, data ) => {
  671. this._hasChangedRange = true;
  672. // If `LiveRange` is in whole moved to the graveyard, save necessary data. It will be fixed on `Model#applyOperation` event.
  673. if ( liveRange.root == this._document.graveyard ) {
  674. this._fixGraveyardRangesData.push( {
  675. liveRange,
  676. sourcePosition: data.deletionPosition
  677. } );
  678. }
  679. } );
  680. return liveRange;
  681. }
  682. // Updates this selection attributes according to its ranges and the {@link module:engine/model/document~Document model document}.
  683. //
  684. // @protected
  685. // @param {Boolean} clearAll
  686. // @fires change:attribute
  687. _updateAttributes( clearAll ) {
  688. const newAttributes = toMap( this._getSurroundingAttributes() );
  689. const oldAttributes = toMap( this.getAttributes() );
  690. if ( clearAll ) {
  691. // If `clearAll` remove all attributes and reset priorities.
  692. this._attributePriority = new Map();
  693. this._attrs = new Map();
  694. } else {
  695. // If not, remove only attributes added with `low` priority.
  696. for ( const [ key, priority ] of this._attributePriority ) {
  697. if ( priority == 'low' ) {
  698. this._attrs.delete( key );
  699. this._attributePriority.delete( key );
  700. }
  701. }
  702. }
  703. this._setAttributesTo( newAttributes );
  704. // Let's evaluate which attributes really changed.
  705. const changed = [];
  706. // First, loop through all attributes that are set on selection right now.
  707. // Check which of them are different than old attributes.
  708. for ( const [ newKey, newValue ] of this.getAttributes() ) {
  709. if ( !oldAttributes.has( newKey ) || oldAttributes.get( newKey ) !== newValue ) {
  710. changed.push( newKey );
  711. }
  712. }
  713. // Then, check which of old attributes got removed.
  714. for ( const [ oldKey ] of oldAttributes ) {
  715. if ( !this.hasAttribute( oldKey ) ) {
  716. changed.push( oldKey );
  717. }
  718. }
  719. // Fire event with exact data (fire only if anything changed).
  720. if ( changed.length > 0 ) {
  721. this.fire( 'change:attribute', { attributeKeys: changed, directChange: false } );
  722. }
  723. }
  724. // Internal method for setting `LiveSelection` attribute. Supports attribute priorities (through `directChange`
  725. // parameter).
  726. //
  727. // @private
  728. // @param {String} key Attribute key.
  729. // @param {*} value Attribute value.
  730. // @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  731. // is caused by `Batch` API.
  732. // @returns {Boolean} Whether value has changed.
  733. _setAttribute( key, value, directChange = true ) {
  734. const priority = directChange ? 'normal' : 'low';
  735. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  736. // Priority too low.
  737. return false;
  738. }
  739. const oldValue = super.getAttribute( key );
  740. // Don't do anything if value has not changed.
  741. if ( oldValue === value ) {
  742. return false;
  743. }
  744. this._attrs.set( key, value );
  745. // Update priorities map.
  746. this._attributePriority.set( key, priority );
  747. return true;
  748. }
  749. // Internal method for removing `LiveSelection` attribute. Supports attribute priorities (through `directChange`
  750. // parameter).
  751. //
  752. // NOTE: Even if attribute is not present in the selection but is provided to this method, it's priority will
  753. // be changed according to `directChange` parameter.
  754. //
  755. // @private
  756. // @param {String} key Attribute key.
  757. // @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  758. // is caused by `Batch` API.
  759. // @returns {Boolean} Whether attribute was removed. May not be true if such attributes didn't exist or the
  760. // existing attribute had higher priority.
  761. _removeAttribute( key, directChange = true ) {
  762. const priority = directChange ? 'normal' : 'low';
  763. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  764. // Priority too low.
  765. return false;
  766. }
  767. // Update priorities map.
  768. this._attributePriority.set( key, priority );
  769. // Don't do anything if value has not changed.
  770. if ( !super.hasAttribute( key ) ) {
  771. return false;
  772. }
  773. this._attrs.delete( key );
  774. return true;
  775. }
  776. // Internal method for setting multiple `LiveSelection` attributes. Supports attribute priorities (through
  777. // `directChange` parameter).
  778. //
  779. // @private
  780. // @param {Map.<String,*>} attrs Iterable object containing attributes to be set.
  781. // @returns {Set.<String>} Changed attribute keys.
  782. _setAttributesTo( attrs ) {
  783. const changed = new Set();
  784. for ( const [ oldKey, oldValue ] of this.getAttributes() ) {
  785. // Do not remove attribute if attribute with same key and value is about to be set.
  786. if ( attrs.get( oldKey ) === oldValue ) {
  787. continue;
  788. }
  789. // All rest attributes will be removed so changed attributes won't change .
  790. this._removeAttribute( oldKey, false );
  791. }
  792. for ( const [ key, value ] of attrs ) {
  793. // Attribute may not be set because of attributes or because same key/value is already added.
  794. const gotAdded = this._setAttribute( key, value, false );
  795. if ( gotAdded ) {
  796. changed.add( key );
  797. }
  798. }
  799. return changed;
  800. }
  801. // Returns an iterable that iterates through all selection attributes stored in current selection's parent.
  802. //
  803. // @protected
  804. // @returns {Iterable.<*>}
  805. * _getStoredAttributes() {
  806. const selectionParent = this.getFirstPosition().parent;
  807. if ( this.isCollapsed && selectionParent.isEmpty ) {
  808. for ( const key of selectionParent.getAttributeKeys() ) {
  809. if ( key.startsWith( storePrefix ) ) {
  810. const realKey = key.substr( storePrefix.length );
  811. yield [ realKey, selectionParent.getAttribute( key ) ];
  812. }
  813. }
  814. }
  815. }
  816. // Checks model text nodes that are closest to the selection's first position and returns attributes of first
  817. // found element. If there are no text nodes in selection's first position parent, it returns selection
  818. // attributes stored in that parent.
  819. //
  820. // @private
  821. // @returns {Iterable.<*>} Collection of attributes.
  822. _getSurroundingAttributes() {
  823. const position = this.getFirstPosition();
  824. const schema = this._model.schema;
  825. let attrs = null;
  826. if ( !this.isCollapsed ) {
  827. // 1. If selection is a range...
  828. const range = this.getFirstRange();
  829. // ...look for a first character node in that range and take attributes from it.
  830. for ( const value of range ) {
  831. // If the item is an object, we don't want to get attributes from its children.
  832. if ( value.item.is( 'element' ) && schema.isObject( value.item ) ) {
  833. break;
  834. }
  835. // This is not an optimal solution because of https://github.com/ckeditor/ckeditor5-engine/issues/454.
  836. // It can be done better by using `break;` instead of checking `attrs === null`.
  837. if ( value.type == 'text' && attrs === null ) {
  838. attrs = value.item.getAttributes();
  839. }
  840. }
  841. } else {
  842. // 2. If the selection is a caret or the range does not contain a character node...
  843. const nodeBefore = position.textNode ? position.textNode : position.nodeBefore;
  844. const nodeAfter = position.textNode ? position.textNode : position.nodeAfter;
  845. // When gravity is overridden then don't take node before into consideration.
  846. if ( !this.isGravityOverridden ) {
  847. // ...look at the node before caret and take attributes from it if it is a character node.
  848. attrs = getAttrsIfCharacter( nodeBefore );
  849. }
  850. // 3. If not, look at the node after caret...
  851. if ( !attrs ) {
  852. attrs = getAttrsIfCharacter( nodeAfter );
  853. }
  854. // 4. If not, try to find the first character on the left, that is in the same node.
  855. // When gravity is overridden then don't take node before into consideration.
  856. if ( !this.isGravityOverridden && !attrs ) {
  857. let node = nodeBefore;
  858. while ( node && !attrs ) {
  859. node = node.previousSibling;
  860. attrs = getAttrsIfCharacter( node );
  861. }
  862. }
  863. // 5. If not found, try to find the first character on the right, that is in the same node.
  864. if ( !attrs ) {
  865. let node = nodeAfter;
  866. while ( node && !attrs ) {
  867. node = node.nextSibling;
  868. attrs = getAttrsIfCharacter( node );
  869. }
  870. }
  871. // 6. If not found, selection should retrieve attributes from parent.
  872. if ( !attrs ) {
  873. attrs = this._getStoredAttributes();
  874. }
  875. }
  876. return attrs;
  877. }
  878. // Fixes a selection range after it ends up in graveyard root.
  879. //
  880. // @private
  881. // @param {module:engine/model/liverange~LiveRange} liveRange The range from selection, that ended up in the graveyard root.
  882. // @param {module:engine/model/position~Position} removedRangeStart Start position of a range which was removed.
  883. _fixGraveyardSelection( liveRange, removedRangeStart ) {
  884. // The start of the removed range is the closest position to the `liveRange` - the original selection range.
  885. // This is a good candidate for a fixed selection range.
  886. const positionCandidate = removedRangeStart.clone();
  887. // Find a range that is a correct selection range and is closest to the start of removed range.
  888. const selectionRange = this._model.schema.getNearestSelectionRange( positionCandidate );
  889. // Remove the old selection range before preparing and adding new selection range. This order is important,
  890. // because new range, in some cases, may intersect with old range (it depends on `getNearestSelectionRange()` result).
  891. const index = this._ranges.indexOf( liveRange );
  892. this._ranges.splice( index, 1 );
  893. liveRange.detach();
  894. // If nearest valid selection range has been found - add it in the place of old range.
  895. if ( selectionRange ) {
  896. // Check the range, convert it to live range, bind events, etc.
  897. const newRange = this._prepareRange( selectionRange );
  898. // Add new range in the place of old range.
  899. this._ranges.splice( index, 0, newRange );
  900. }
  901. // If nearest valid selection range cannot be found - just removing the old range is fine.
  902. }
  903. }
  904. // Helper function for {@link module:engine/model/liveselection~LiveSelection#_updateAttributes}.
  905. //
  906. // It takes model item, checks whether it is a text node (or text proxy) and, if so, returns it's attributes. If not, returns `null`.
  907. //
  908. // @param {module:engine/model/item~Item|null} node
  909. // @returns {Boolean}
  910. function getAttrsIfCharacter( node ) {
  911. if ( node instanceof TextProxy || node instanceof Text ) {
  912. return node.getAttributes();
  913. }
  914. return null;
  915. }
  916. // Removes selection attributes from element which is not empty anymore.
  917. //
  918. // @private
  919. // @param {module:engine/model/model~Model} model
  920. // @param {module:engine/model/batch~Batch} batch
  921. function clearAttributesStoredInElement( model, batch ) {
  922. const differ = model.document.differ;
  923. for ( const entry of differ.getChanges() ) {
  924. if ( entry.type != 'insert' ) {
  925. continue;
  926. }
  927. const changeParent = entry.position.parent;
  928. const isNoLongerEmpty = entry.length === changeParent.maxOffset;
  929. if ( isNoLongerEmpty ) {
  930. model.enqueueChange( batch, writer => {
  931. const storedAttributes = Array.from( changeParent.getAttributeKeys() )
  932. .filter( key => key.startsWith( storePrefix ) );
  933. for ( const key of storedAttributes ) {
  934. writer.removeAttribute( key, changeParent );
  935. }
  936. } );
  937. }
  938. }
  939. }