documentselection.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/documentselection
  7. */
  8. import Position from './position';
  9. import Range from './range';
  10. import LiveRange from './liverange';
  11. import Text from './text';
  12. import TextProxy from './textproxy';
  13. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  14. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  15. import log from '@ckeditor/ckeditor5-utils/src/log';
  16. import Selection from './selection';
  17. const storePrefix = 'selection:';
  18. const attrOpTypes = new Set(
  19. [ 'addAttribute', 'removeAttribute', 'changeAttribute', 'addRootAttribute', 'removeRootAttribute', 'changeRootAttribute' ]
  20. );
  21. /**
  22. * `DocumentSelection` is a special selection which is used as the
  23. * {@link module:engine/model/document~Document#selection document's selection}.
  24. * There can be only one instance of `DocumentSelection` per document.
  25. *
  26. * `DocumentSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
  27. * to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
  28. *
  29. * Differences between {@link module:engine/model/selection~Selection} and `DocumentSelection` are:
  30. * * there is always a range in `DocumentSelection` - even if no ranges were added there is a "default range"
  31. * present in the selection,
  32. * * ranges added to this selection updates automatically when the document changes,
  33. * * attributes of `DocumentSelection` are updated automatically according to selection ranges.
  34. *
  35. * Since `DocumentSelection` uses {@link module:engine/model/liverange~LiveRange live ranges}
  36. * and is updated when {@link module:engine/model/document~Document document}
  37. * changes, it cannot be set on {@link module:engine/model/node~Node nodes}
  38. * that are inside {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
  39. * If you need to represent a selection in document fragment,
  40. * use {@link module:engine/model/selection~Selection Selection class} instead.
  41. *
  42. * @extends module:engine/model/selection~Selection
  43. */
  44. export default class DocumentSelection extends Selection {
  45. /**
  46. * Creates an empty live selection for given {@link module:engine/model/document~Document}.
  47. *
  48. * @param {module:engine/model/document~Document} document Document which owns this selection.
  49. */
  50. constructor( document ) {
  51. super();
  52. /**
  53. * Document which owns this selection.
  54. *
  55. * @protected
  56. * @member {module:engine/model/document~Document} module:engine/model/documentselection~DocumentSelection#_document
  57. */
  58. this._document = document;
  59. /**
  60. * Keeps mapping of attribute name to priority with which the attribute got modified (added/changed/removed)
  61. * last time. Possible values of priority are: `'low'` and `'normal'`.
  62. *
  63. * Priorities are used by internal `DocumentSelection` mechanisms. All attributes set using `DocumentSelection`
  64. * attributes API are set with `'normal'` priority.
  65. *
  66. * @private
  67. * @member {Map} module:engine/model/documentselection~DocumentSelection#_attributePriority
  68. */
  69. this._attributePriority = new Map();
  70. this.listenTo( this._document, 'change', ( evt, type, changes, batch ) => {
  71. // Whenever attribute operation is performed on document, update selection attributes.
  72. // This is not the most efficient way to update selection attributes, but should be okay for now.
  73. if ( attrOpTypes.has( type ) ) {
  74. this._updateAttributes( false );
  75. }
  76. // Whenever element which had selection's attributes stored in it stops being empty,
  77. // the attributes need to be removed.
  78. clearAttributesStoredInElement( changes, batch, this._document );
  79. } );
  80. }
  81. /**
  82. * @inheritDoc
  83. */
  84. get isCollapsed() {
  85. const length = this._ranges.length;
  86. return length === 0 ? this._document._getDefaultRange().isCollapsed : super.isCollapsed;
  87. }
  88. /**
  89. * @inheritDoc
  90. */
  91. get anchor() {
  92. return super.anchor || this._document._getDefaultRange().start;
  93. }
  94. /**
  95. * @inheritDoc
  96. */
  97. get focus() {
  98. return super.focus || this._document._getDefaultRange().end;
  99. }
  100. /**
  101. * @inheritDoc
  102. */
  103. get rangeCount() {
  104. return this._ranges.length ? this._ranges.length : 1;
  105. }
  106. /**
  107. * Describes whether `DocumentSelection` has own range(s) set, or if it is defaulted to
  108. * {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
  109. *
  110. * @readonly
  111. * @type {Boolean}
  112. */
  113. get hasOwnRange() {
  114. return this._ranges.length > 0;
  115. }
  116. /**
  117. * Unbinds all events previously bound by document selection.
  118. */
  119. destroy() {
  120. for ( let i = 0; i < this._ranges.length; i++ ) {
  121. this._ranges[ i ].detach();
  122. }
  123. this.stopListening();
  124. }
  125. /**
  126. * @inheritDoc
  127. */
  128. * getRanges() {
  129. if ( this._ranges.length ) {
  130. yield* super.getRanges();
  131. } else {
  132. yield this._document._getDefaultRange();
  133. }
  134. }
  135. /**
  136. * @inheritDoc
  137. */
  138. getFirstRange() {
  139. return super.getFirstRange() || this._document._getDefaultRange();
  140. }
  141. /**
  142. * @inheritDoc
  143. */
  144. getLastRange() {
  145. return super.getLastRange() || this._document._getDefaultRange();
  146. }
  147. /**
  148. * @inheritDoc
  149. */
  150. addRange( range, isBackward = false ) {
  151. super.addRange( range, isBackward );
  152. this.refreshAttributes();
  153. }
  154. /**
  155. * @inheritDoc
  156. */
  157. removeAllRanges() {
  158. super.removeAllRanges();
  159. this.refreshAttributes();
  160. }
  161. /**
  162. * @inheritDoc
  163. */
  164. setRanges( newRanges, isLastBackward = false ) {
  165. super.setRanges( newRanges, isLastBackward );
  166. this.refreshAttributes();
  167. }
  168. /**
  169. * @inheritDoc
  170. */
  171. setAttribute( key, value ) {
  172. // Store attribute in parent element if the selection is collapsed in an empty node.
  173. if ( this.isCollapsed && this.anchor.parent.isEmpty ) {
  174. this._storeAttribute( key, value );
  175. }
  176. if ( this._setAttribute( key, value ) ) {
  177. // Fire event with exact data.
  178. const attributeKeys = [ key ];
  179. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  180. }
  181. }
  182. /**
  183. * @inheritDoc
  184. */
  185. removeAttribute( key ) {
  186. // Remove stored attribute from parent element if the selection is collapsed in an empty node.
  187. if ( this.isCollapsed && this.anchor.parent.isEmpty ) {
  188. this._removeStoredAttribute( key );
  189. }
  190. if ( this._removeAttribute( key ) ) {
  191. // Fire event with exact data.
  192. const attributeKeys = [ key ];
  193. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  194. }
  195. }
  196. /**
  197. * @inheritDoc
  198. */
  199. setAttributesTo( attrs ) {
  200. attrs = toMap( attrs );
  201. if ( this.isCollapsed && this.anchor.parent.isEmpty ) {
  202. this._setStoredAttributesTo( attrs );
  203. }
  204. const changed = this._setAttributesTo( attrs );
  205. if ( changed.size > 0 ) {
  206. // Fire event with exact data (fire only if anything changed).
  207. const attributeKeys = Array.from( changed );
  208. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  209. }
  210. }
  211. /**
  212. * @inheritDoc
  213. */
  214. clearAttributes() {
  215. this.setAttributesTo( [] );
  216. }
  217. /**
  218. * Removes all attributes from the selection and sets attributes according to the surrounding nodes.
  219. */
  220. refreshAttributes() {
  221. this._updateAttributes( true );
  222. }
  223. /**
  224. * This method is not available in `DocumentSelection`. There can be only one
  225. * `DocumentSelection` per document instance, so creating new `DocumentSelection`s this way
  226. * would be unsafe.
  227. */
  228. static createFromSelection() {
  229. /**
  230. * `DocumentSelection#createFromSelection()` is not available. There can be only one
  231. * `DocumentSelection` per document instance, so creating new `DocumentSelection`s this way
  232. * would be unsafe.
  233. *
  234. * @error documentselection-cannot-create
  235. */
  236. throw new CKEditorError( 'documentselection-cannot-create: Cannot create new DocumentSelection instance.' );
  237. }
  238. /**
  239. * @inheritDoc
  240. */
  241. _popRange() {
  242. this._ranges.pop().detach();
  243. }
  244. /**
  245. * @inheritDoc
  246. */
  247. _pushRange( range ) {
  248. const liveRange = this._prepareRange( range );
  249. // `undefined` is returned when given `range` is in graveyard root.
  250. if ( liveRange ) {
  251. this._ranges.push( liveRange );
  252. }
  253. }
  254. /**
  255. * Prepares given range to be added to selection. Checks if it is correct,
  256. * converts it to {@link module:engine/model/liverange~LiveRange LiveRange}
  257. * and sets listeners listening to the range's change event.
  258. *
  259. * @private
  260. * @param {module:engine/model/range~Range} range
  261. */
  262. _prepareRange( range ) {
  263. if ( !( range instanceof Range ) ) {
  264. /**
  265. * Trying to add an object that is not an instance of Range.
  266. *
  267. * @error model-selection-added-not-range
  268. */
  269. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  270. }
  271. if ( range.root == this._document.graveyard ) {
  272. /**
  273. * Trying to add a Range that is in the graveyard root. Range rejected.
  274. *
  275. * @warning model-selection-range-in-graveyard
  276. */
  277. log.warn( 'model-selection-range-in-graveyard: Trying to add a Range that is in the graveyard root. Range rejected.' );
  278. return;
  279. }
  280. this._checkRange( range );
  281. const liveRange = LiveRange.createFromRange( range );
  282. this.listenTo( liveRange, 'change:range', ( evt, oldRange, data ) => {
  283. // If `LiveRange` is in whole moved to the graveyard, fix that range.
  284. if ( liveRange.root == this._document.graveyard ) {
  285. const sourceStart = data.sourcePosition;
  286. const howMany = data.range.end.offset - data.range.start.offset;
  287. const sourceRange = Range.createFromPositionAndShift( sourceStart, howMany );
  288. this._fixGraveyardSelection( liveRange, sourceRange );
  289. }
  290. // Whenever a live range from selection changes, fire an event informing about that change.
  291. this.fire( 'change:range', { directChange: false } );
  292. } );
  293. return liveRange;
  294. }
  295. /**
  296. * Updates this selection attributes according to its ranges and the {@link module:engine/model/document~Document model document}.
  297. *
  298. * @protected
  299. * @param {Boolean} clearAll
  300. * @fires change:attribute
  301. */
  302. _updateAttributes( clearAll ) {
  303. const newAttributes = toMap( this._getSurroundingAttributes() );
  304. const oldAttributes = toMap( this.getAttributes() );
  305. if ( clearAll ) {
  306. // If `clearAll` remove all attributes and reset priorities.
  307. this._attributePriority = new Map();
  308. this._attrs = new Map();
  309. } else {
  310. // If not, remove only attributes added with `low` priority.
  311. for ( const [ key, priority ] of this._attributePriority ) {
  312. if ( priority == 'low' ) {
  313. this._attrs.delete( key );
  314. this._attributePriority.delete( key );
  315. }
  316. }
  317. }
  318. this._setAttributesTo( newAttributes, false );
  319. // Let's evaluate which attributes really changed.
  320. const changed = [];
  321. // First, loop through all attributes that are set on selection right now.
  322. // Check which of them are different than old attributes.
  323. for ( const [ newKey, newValue ] of this.getAttributes() ) {
  324. if ( !oldAttributes.has( newKey ) || oldAttributes.get( newKey ) !== newValue ) {
  325. changed.push( newKey );
  326. }
  327. }
  328. // Then, check which of old attributes got removed.
  329. for ( const [ oldKey ] of oldAttributes ) {
  330. if ( !this.hasAttribute( oldKey ) ) {
  331. changed.push( oldKey );
  332. }
  333. }
  334. // Fire event with exact data (fire only if anything changed).
  335. if ( changed.length > 0 ) {
  336. this.fire( 'change:attribute', { attributeKeys: changed, directChange: false } );
  337. }
  338. }
  339. /**
  340. * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
  341. *
  342. * @protected
  343. * @param {String} key Attribute key to convert.
  344. * @returns {String} Converted attribute key, applicable for selection store.
  345. */
  346. static _getStoreAttributeKey( key ) {
  347. return storePrefix + key;
  348. }
  349. /**
  350. * Checks whether the given attribute key is an attribute stored on an element.
  351. *
  352. * @protected
  353. * @param {String} key
  354. * @returns {Boolean}
  355. */
  356. static _isStoreAttributeKey( key ) {
  357. return key.startsWith( storePrefix );
  358. }
  359. /**
  360. * Internal method for setting `DocumentSelection` attribute. Supports attribute priorities (through `directChange`
  361. * parameter).
  362. *
  363. * @private
  364. * @param {String} key Attribute key.
  365. * @param {*} value Attribute value.
  366. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  367. * is caused by `Batch` API.
  368. * @returns {Boolean} Whether value has changed.
  369. */
  370. _setAttribute( key, value, directChange = true ) {
  371. const priority = directChange ? 'normal' : 'low';
  372. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  373. // Priority too low.
  374. return false;
  375. }
  376. const oldValue = super.getAttribute( key );
  377. // Don't do anything if value has not changed.
  378. if ( oldValue === value ) {
  379. return false;
  380. }
  381. this._attrs.set( key, value );
  382. // Update priorities map.
  383. this._attributePriority.set( key, priority );
  384. return true;
  385. }
  386. /**
  387. * Internal method for removing `DocumentSelection` attribute. Supports attribute priorities (through `directChange`
  388. * parameter).
  389. *
  390. * @private
  391. * @param {String} key Attribute key.
  392. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  393. * is caused by `Batch` API.
  394. * @returns {Boolean} Whether attribute was removed. May not be true if such attributes didn't exist or the
  395. * existing attribute had higher priority.
  396. */
  397. _removeAttribute( key, directChange = true ) {
  398. const priority = directChange ? 'normal' : 'low';
  399. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  400. // Priority too low.
  401. return false;
  402. }
  403. // Don't do anything if value has not changed.
  404. if ( !super.hasAttribute( key ) ) {
  405. return false;
  406. }
  407. this._attrs.delete( key );
  408. // Update priorities map.
  409. this._attributePriority.set( key, priority );
  410. return true;
  411. }
  412. /**
  413. * Internal method for setting multiple `DocumentSelection` attributes. Supports attribute priorities (through
  414. * `directChange` parameter).
  415. *
  416. * @private
  417. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  418. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  419. * is caused by `Batch` API.
  420. * @returns {Set.<String>} Changed attribute keys.
  421. */
  422. _setAttributesTo( attrs, directChange = true ) {
  423. const changed = new Set();
  424. for ( const [ oldKey, oldValue ] of this.getAttributes() ) {
  425. // Do not remove attribute if attribute with same key and value is about to be set.
  426. if ( attrs.get( oldKey ) === oldValue ) {
  427. continue;
  428. }
  429. // Attribute still might not get removed because of priorities.
  430. if ( this._removeAttribute( oldKey, directChange ) ) {
  431. changed.add( oldKey );
  432. }
  433. }
  434. for ( const [ key, value ] of attrs ) {
  435. // Attribute may not be set because of attributes or because same key/value is already added.
  436. const gotAdded = this._setAttribute( key, value, directChange );
  437. if ( gotAdded ) {
  438. changed.add( key );
  439. }
  440. }
  441. return changed;
  442. }
  443. /**
  444. * Returns an iterator that iterates through all selection attributes stored in current selection's parent.
  445. *
  446. * @private
  447. * @returns {Iterable.<*>}
  448. */
  449. * _getStoredAttributes() {
  450. const selectionParent = this.getFirstPosition().parent;
  451. if ( this.isCollapsed && selectionParent.isEmpty ) {
  452. for ( const key of selectionParent.getAttributeKeys() ) {
  453. if ( key.startsWith( storePrefix ) ) {
  454. const realKey = key.substr( storePrefix.length );
  455. yield [ realKey, selectionParent.getAttribute( key ) ];
  456. }
  457. }
  458. }
  459. }
  460. /**
  461. * Removes attribute with given key from attributes stored in current selection's parent node.
  462. *
  463. * @private
  464. * @param {String} key Key of attribute to remove.
  465. */
  466. _removeStoredAttribute( key ) {
  467. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  468. this._document.batch().removeAttribute( this.anchor.parent, storeKey );
  469. }
  470. /**
  471. * Stores given attribute key and value in current selection's parent node.
  472. *
  473. * @private
  474. * @param {String} key Key of attribute to set.
  475. * @param {*} value Attribute value.
  476. */
  477. _storeAttribute( key, value ) {
  478. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  479. this._document.batch().setAttribute( this.anchor.parent, storeKey, value );
  480. }
  481. /**
  482. * Sets selection attributes stored in current selection's parent node to given set of attributes.
  483. *
  484. * @private
  485. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  486. */
  487. _setStoredAttributesTo( attrs ) {
  488. const selectionParent = this.anchor.parent;
  489. const batch = this._document.batch();
  490. for ( const [ oldKey ] of this._getStoredAttributes() ) {
  491. const storeKey = DocumentSelection._getStoreAttributeKey( oldKey );
  492. batch.removeAttribute( selectionParent, storeKey );
  493. }
  494. for ( const [ key, value ] of attrs ) {
  495. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  496. batch.setAttribute( selectionParent, storeKey, value );
  497. }
  498. }
  499. /**
  500. * Checks model text nodes that are closest to the selection's first position and returns attributes of first
  501. * found element. If there are no text nodes in selection's first position parent, it returns selection
  502. * attributes stored in that parent.
  503. *
  504. * @private
  505. * @returns {Iterable.<*>} Collection of attributes.
  506. */
  507. _getSurroundingAttributes() {
  508. const position = this.getFirstPosition();
  509. const schema = this._document.schema;
  510. let attrs = null;
  511. if ( !this.isCollapsed ) {
  512. // 1. If selection is a range...
  513. const range = this.getFirstRange();
  514. // ...look for a first character node in that range and take attributes from it.
  515. for ( const value of range ) {
  516. // If the item is an object, we don't want to get attributes from its children.
  517. if ( value.item.is( 'element' ) && schema.objects.has( value.item.name ) ) {
  518. break;
  519. }
  520. // This is not an optimal solution because of https://github.com/ckeditor/ckeditor5-engine/issues/454.
  521. // It can be done better by using `break;` instead of checking `attrs === null`.
  522. if ( value.type == 'text' && attrs === null ) {
  523. attrs = value.item.getAttributes();
  524. }
  525. }
  526. } else {
  527. // 2. If the selection is a caret or the range does not contain a character node...
  528. const nodeBefore = position.textNode ? position.textNode : position.nodeBefore;
  529. const nodeAfter = position.textNode ? position.textNode : position.nodeAfter;
  530. // ...look at the node before caret and take attributes from it if it is a character node.
  531. attrs = getAttrsIfCharacter( nodeBefore );
  532. // 3. If not, look at the node after caret...
  533. if ( !attrs ) {
  534. attrs = getAttrsIfCharacter( nodeAfter );
  535. }
  536. // 4. If not, try to find the first character on the left, that is in the same node.
  537. if ( !attrs ) {
  538. let node = nodeBefore;
  539. while ( node && !attrs ) {
  540. node = node.previousSibling;
  541. attrs = getAttrsIfCharacter( node );
  542. }
  543. }
  544. // 5. If not found, try to find the first character on the right, that is in the same node.
  545. if ( !attrs ) {
  546. let node = nodeAfter;
  547. while ( node && !attrs ) {
  548. node = node.nextSibling;
  549. attrs = getAttrsIfCharacter( node );
  550. }
  551. }
  552. // 6. If not found, selection should retrieve attributes from parent.
  553. if ( !attrs ) {
  554. attrs = this._getStoredAttributes();
  555. }
  556. }
  557. return attrs;
  558. }
  559. /**
  560. * Fixes a selection range after it ends up in graveyard root.
  561. *
  562. * @private
  563. * @param {module:engine/model/liverange~LiveRange} liveRange The range from selection, that ended up in the graveyard root.
  564. * @param {module:engine/model/range~Range} removedRange Range which removing had caused moving `liveRange` to the graveyard root.
  565. */
  566. _fixGraveyardSelection( liveRange, removedRange ) {
  567. // The start of the removed range is the closest position to the `liveRange` - the original selection range.
  568. // This is a good candidate for a fixed selection range.
  569. const positionCandidate = Position.createFromPosition( removedRange.start );
  570. // Find a range that is a correct selection range and is closest to the start of removed range.
  571. const selectionRange = this._document.getNearestSelectionRange( positionCandidate );
  572. // Remove the old selection range before preparing and adding new selection range. This order is important,
  573. // because new range, in some cases, may intersect with old range (it depends on `getNearestSelectionRange()` result).
  574. const index = this._ranges.indexOf( liveRange );
  575. this._ranges.splice( index, 1 );
  576. liveRange.detach();
  577. // If nearest valid selection range has been found - add it in the place of old range.
  578. if ( selectionRange ) {
  579. // Check the range, convert it to live range, bind events, etc.
  580. const newRange = this._prepareRange( selectionRange );
  581. // Add new range in the place of old range.
  582. this._ranges.splice( index, 0, newRange );
  583. }
  584. // If nearest valid selection range cannot be found - just removing the old range is fine.
  585. // Fire an event informing about selection change.
  586. this.fire( 'change:range', { directChange: false } );
  587. }
  588. }
  589. /**
  590. * @event change:attribute
  591. */
  592. // Helper function for {@link module:engine/model/documentselection~DocumentSelection#_updateAttributes}.
  593. //
  594. // 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`.
  595. //
  596. // @param {module:engine/model/item~Item|null} node
  597. // @returns {Boolean}
  598. function getAttrsIfCharacter( node ) {
  599. if ( node instanceof TextProxy || node instanceof Text ) {
  600. return node.getAttributes();
  601. }
  602. return null;
  603. }
  604. // Removes selection attributes from element which is not empty anymore.
  605. function clearAttributesStoredInElement( changes, batch, document ) {
  606. // Batch may not be passed to the document#change event in some tests.
  607. // See https://github.com/ckeditor/ckeditor5-engine/issues/1001#issuecomment-314202352
  608. // Ignore also transparent batches because they are... transparent.
  609. if ( !batch || batch.type == 'transparent' ) {
  610. return;
  611. }
  612. const changeParent = changes.range && changes.range.start.parent;
  613. // `changes.range` is not set in case of rename, root and marker operations.
  614. // None of them may lead to the element becoming non-empty.
  615. if ( !changeParent || changeParent.isEmpty ) {
  616. return;
  617. }
  618. document.enqueueChanges( () => {
  619. const storedAttributes = Array.from( changeParent.getAttributeKeys() ).filter( key => key.startsWith( storePrefix ) );
  620. for ( const key of storedAttributes ) {
  621. batch.removeAttribute( changeParent, key );
  622. }
  623. } );
  624. }