8
0

documentselection.js 38 KB

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