documentselection.js 30 KB

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