8
0

documentselection.js 34 KB

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