documentselection.js 38 KB

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