documentselection.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. * Cannot create a new `DocumentSelection` instance.
  231. *
  232. * `DocumentSelection#createFromSelection()` is not available. There can be only one
  233. * `DocumentSelection` per document instance, so creating new `DocumentSelection`s this way
  234. * would be unsafe.
  235. *
  236. * @error documentselection-cannot-create
  237. */
  238. throw new CKEditorError( 'documentselection-cannot-create: Cannot create a new DocumentSelection instance.' );
  239. }
  240. /**
  241. * @inheritDoc
  242. */
  243. _popRange() {
  244. this._ranges.pop().detach();
  245. }
  246. /**
  247. * @inheritDoc
  248. */
  249. _pushRange( range ) {
  250. const liveRange = this._prepareRange( range );
  251. // `undefined` is returned when given `range` is in graveyard root.
  252. if ( liveRange ) {
  253. this._ranges.push( liveRange );
  254. }
  255. }
  256. /**
  257. * Prepares given range to be added to selection. Checks if it is correct,
  258. * converts it to {@link module:engine/model/liverange~LiveRange LiveRange}
  259. * and sets listeners listening to the range's change event.
  260. *
  261. * @private
  262. * @param {module:engine/model/range~Range} range
  263. */
  264. _prepareRange( range ) {
  265. if ( !( range instanceof Range ) ) {
  266. /**
  267. * Trying to add an object that is not an instance of Range.
  268. *
  269. * @error model-selection-added-not-range
  270. */
  271. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  272. }
  273. if ( range.root == this._document.graveyard ) {
  274. /**
  275. * Trying to add a Range that is in the graveyard root. Range rejected.
  276. *
  277. * @warning model-selection-range-in-graveyard
  278. */
  279. log.warn( 'model-selection-range-in-graveyard: Trying to add a Range that is in the graveyard root. Range rejected.' );
  280. return;
  281. }
  282. this._checkRange( range );
  283. const liveRange = LiveRange.createFromRange( range );
  284. liveRange.on( 'change:range', ( evt, oldRange, data ) => {
  285. // If `LiveRange` is in whole moved to the graveyard, fix that range.
  286. if ( liveRange.root == this._document.graveyard ) {
  287. this._fixGraveyardSelection( liveRange, data.sourcePosition );
  288. }
  289. // Whenever a live range from selection changes, fire an event informing about that change.
  290. this.fire( 'change:range', { directChange: false } );
  291. } );
  292. return liveRange;
  293. }
  294. /**
  295. * Updates this selection attributes according to its ranges and the {@link module:engine/model/document~Document model document}.
  296. *
  297. * @protected
  298. * @param {Boolean} clearAll
  299. * @fires change:attribute
  300. */
  301. _updateAttributes( clearAll ) {
  302. const newAttributes = toMap( this._getSurroundingAttributes() );
  303. const oldAttributes = toMap( this.getAttributes() );
  304. if ( clearAll ) {
  305. // If `clearAll` remove all attributes and reset priorities.
  306. this._attributePriority = new Map();
  307. this._attrs = new Map();
  308. } else {
  309. // If not, remove only attributes added with `low` priority.
  310. for ( const [ key, priority ] of this._attributePriority ) {
  311. if ( priority == 'low' ) {
  312. this._attrs.delete( key );
  313. this._attributePriority.delete( key );
  314. }
  315. }
  316. }
  317. this._setAttributesTo( newAttributes, false );
  318. // Let's evaluate which attributes really changed.
  319. const changed = [];
  320. // First, loop through all attributes that are set on selection right now.
  321. // Check which of them are different than old attributes.
  322. for ( const [ newKey, newValue ] of this.getAttributes() ) {
  323. if ( !oldAttributes.has( newKey ) || oldAttributes.get( newKey ) !== newValue ) {
  324. changed.push( newKey );
  325. }
  326. }
  327. // Then, check which of old attributes got removed.
  328. for ( const [ oldKey ] of oldAttributes ) {
  329. if ( !this.hasAttribute( oldKey ) ) {
  330. changed.push( oldKey );
  331. }
  332. }
  333. // Fire event with exact data (fire only if anything changed).
  334. if ( changed.length > 0 ) {
  335. this.fire( 'change:attribute', { attributeKeys: changed, directChange: false } );
  336. }
  337. }
  338. /**
  339. * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
  340. *
  341. * @protected
  342. * @param {String} key Attribute key to convert.
  343. * @returns {String} Converted attribute key, applicable for selection store.
  344. */
  345. static _getStoreAttributeKey( key ) {
  346. return storePrefix + key;
  347. }
  348. /**
  349. * Checks whether the given attribute key is an attribute stored on an element.
  350. *
  351. * @protected
  352. * @param {String} key
  353. * @returns {Boolean}
  354. */
  355. static _isStoreAttributeKey( key ) {
  356. return key.startsWith( storePrefix );
  357. }
  358. /**
  359. * Internal method for setting `DocumentSelection` attribute. Supports attribute priorities (through `directChange`
  360. * parameter).
  361. *
  362. * @private
  363. * @param {String} key Attribute key.
  364. * @param {*} value Attribute value.
  365. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  366. * is caused by `Batch` API.
  367. * @returns {Boolean} Whether value has changed.
  368. */
  369. _setAttribute( key, value, directChange = true ) {
  370. const priority = directChange ? 'normal' : 'low';
  371. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  372. // Priority too low.
  373. return false;
  374. }
  375. const oldValue = super.getAttribute( key );
  376. // Don't do anything if value has not changed.
  377. if ( oldValue === value ) {
  378. return false;
  379. }
  380. this._attrs.set( key, value );
  381. // Update priorities map.
  382. this._attributePriority.set( key, priority );
  383. return true;
  384. }
  385. /**
  386. * Internal method for removing `DocumentSelection` attribute. Supports attribute priorities (through `directChange`
  387. * parameter).
  388. *
  389. * @private
  390. * @param {String} key Attribute key.
  391. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  392. * is caused by `Batch` API.
  393. * @returns {Boolean} Whether attribute was removed. May not be true if such attributes didn't exist or the
  394. * existing attribute had higher priority.
  395. */
  396. _removeAttribute( key, directChange = true ) {
  397. const priority = directChange ? 'normal' : 'low';
  398. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  399. // Priority too low.
  400. return false;
  401. }
  402. // Don't do anything if value has not changed.
  403. if ( !super.hasAttribute( key ) ) {
  404. return false;
  405. }
  406. this._attrs.delete( key );
  407. // Update priorities map.
  408. this._attributePriority.set( key, priority );
  409. return true;
  410. }
  411. /**
  412. * Internal method for setting multiple `DocumentSelection` attributes. Supports attribute priorities (through
  413. * `directChange` parameter).
  414. *
  415. * @private
  416. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  417. * @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  418. * is caused by `Batch` API.
  419. * @returns {Set.<String>} Changed attribute keys.
  420. */
  421. _setAttributesTo( attrs, directChange = true ) {
  422. const changed = new Set();
  423. for ( const [ oldKey, oldValue ] of this.getAttributes() ) {
  424. // Do not remove attribute if attribute with same key and value is about to be set.
  425. if ( attrs.get( oldKey ) === oldValue ) {
  426. continue;
  427. }
  428. // Attribute still might not get removed because of priorities.
  429. if ( this._removeAttribute( oldKey, directChange ) ) {
  430. changed.add( oldKey );
  431. }
  432. }
  433. for ( const [ key, value ] of attrs ) {
  434. // Attribute may not be set because of attributes or because same key/value is already added.
  435. const gotAdded = this._setAttribute( key, value, directChange );
  436. if ( gotAdded ) {
  437. changed.add( key );
  438. }
  439. }
  440. return changed;
  441. }
  442. /**
  443. * Returns an iterator that iterates through all selection attributes stored in current selection's parent.
  444. *
  445. * @private
  446. * @returns {Iterable.<*>}
  447. */
  448. * _getStoredAttributes() {
  449. const selectionParent = this.getFirstPosition().parent;
  450. if ( this.isCollapsed && selectionParent.isEmpty ) {
  451. for ( const key of selectionParent.getAttributeKeys() ) {
  452. if ( key.startsWith( storePrefix ) ) {
  453. const realKey = key.substr( storePrefix.length );
  454. yield [ realKey, selectionParent.getAttribute( key ) ];
  455. }
  456. }
  457. }
  458. }
  459. /**
  460. * Removes attribute with given key from attributes stored in current selection's parent node.
  461. *
  462. * @private
  463. * @param {String} key Key of attribute to remove.
  464. */
  465. _removeStoredAttribute( key ) {
  466. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  467. this._document.batch().removeAttribute( storeKey, this.anchor.parent );
  468. }
  469. /**
  470. * Stores given attribute key and value in current selection's parent node.
  471. *
  472. * @private
  473. * @param {String} key Key of attribute to set.
  474. * @param {*} value Attribute value.
  475. */
  476. _storeAttribute( key, value ) {
  477. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  478. this._document.batch().setAttribute( storeKey, value, this.anchor.parent );
  479. }
  480. /**
  481. * Sets selection attributes stored in current selection's parent node to given set of attributes.
  482. *
  483. * @private
  484. * @param {Iterable|Object} attrs Iterable object containing attributes to be set.
  485. */
  486. _setStoredAttributesTo( attrs ) {
  487. const selectionParent = this.anchor.parent;
  488. const batch = this._document.batch();
  489. for ( const [ oldKey ] of this._getStoredAttributes() ) {
  490. const storeKey = DocumentSelection._getStoreAttributeKey( oldKey );
  491. batch.removeAttribute( storeKey, selectionParent );
  492. }
  493. for ( const [ key, value ] of attrs ) {
  494. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  495. batch.setAttribute( storeKey, value, selectionParent );
  496. }
  497. }
  498. /**
  499. * Checks model text nodes that are closest to the selection's first position and returns attributes of first
  500. * found element. If there are no text nodes in selection's first position parent, it returns selection
  501. * attributes stored in that parent.
  502. *
  503. * @private
  504. * @returns {Iterable.<*>} Collection of attributes.
  505. */
  506. _getSurroundingAttributes() {
  507. const position = this.getFirstPosition();
  508. const schema = this._document.schema;
  509. let attrs = null;
  510. if ( !this.isCollapsed ) {
  511. // 1. If selection is a range...
  512. const range = this.getFirstRange();
  513. // ...look for a first character node in that range and take attributes from it.
  514. for ( const value of range ) {
  515. // If the item is an object, we don't want to get attributes from its children.
  516. if ( value.item.is( 'element' ) && schema.objects.has( value.item.name ) ) {
  517. break;
  518. }
  519. // This is not an optimal solution because of https://github.com/ckeditor/ckeditor5-engine/issues/454.
  520. // It can be done better by using `break;` instead of checking `attrs === null`.
  521. if ( value.type == 'text' && attrs === null ) {
  522. attrs = value.item.getAttributes();
  523. }
  524. }
  525. } else {
  526. // 2. If the selection is a caret or the range does not contain a character node...
  527. const nodeBefore = position.textNode ? position.textNode : position.nodeBefore;
  528. const nodeAfter = position.textNode ? position.textNode : position.nodeAfter;
  529. // ...look at the node before caret and take attributes from it if it is a character node.
  530. attrs = getAttrsIfCharacter( nodeBefore );
  531. // 3. If not, look at the node after caret...
  532. if ( !attrs ) {
  533. attrs = getAttrsIfCharacter( nodeAfter );
  534. }
  535. // 4. If not, try to find the first character on the left, that is in the same node.
  536. if ( !attrs ) {
  537. let node = nodeBefore;
  538. while ( node && !attrs ) {
  539. node = node.previousSibling;
  540. attrs = getAttrsIfCharacter( node );
  541. }
  542. }
  543. // 5. If not found, try to find the first character on the right, that is in the same node.
  544. if ( !attrs ) {
  545. let node = nodeAfter;
  546. while ( node && !attrs ) {
  547. node = node.nextSibling;
  548. attrs = getAttrsIfCharacter( node );
  549. }
  550. }
  551. // 6. If not found, selection should retrieve attributes from parent.
  552. if ( !attrs ) {
  553. attrs = this._getStoredAttributes();
  554. }
  555. }
  556. return attrs;
  557. }
  558. /**
  559. * Fixes a selection range after it ends up in graveyard root.
  560. *
  561. * @private
  562. * @param {module:engine/model/liverange~LiveRange} liveRange The range from selection, that ended up in the graveyard root.
  563. * @param {module:engine/model/position~Position} removedRangeStart Start position of a range which was removed.
  564. */
  565. _fixGraveyardSelection( liveRange, removedRangeStart ) {
  566. // The start of the removed range is the closest position to the `liveRange` - the original selection range.
  567. // This is a good candidate for a fixed selection range.
  568. const positionCandidate = Position.createFromPosition( removedRangeStart );
  569. // Find a range that is a correct selection range and is closest to the start of removed range.
  570. const selectionRange = this._document.getNearestSelectionRange( positionCandidate );
  571. // Remove the old selection range before preparing and adding new selection range. This order is important,
  572. // because new range, in some cases, may intersect with old range (it depends on `getNearestSelectionRange()` result).
  573. const index = this._ranges.indexOf( liveRange );
  574. this._ranges.splice( index, 1 );
  575. liveRange.detach();
  576. // If nearest valid selection range has been found - add it in the place of old range.
  577. if ( selectionRange ) {
  578. // Check the range, convert it to live range, bind events, etc.
  579. const newRange = this._prepareRange( selectionRange );
  580. // Add new range in the place of old range.
  581. this._ranges.splice( index, 0, newRange );
  582. }
  583. // If nearest valid selection range cannot be found - just removing the old range is fine.
  584. // Fire an event informing about selection change.
  585. this.fire( 'change:range', { directChange: false } );
  586. }
  587. }
  588. /**
  589. * @event change:attribute
  590. */
  591. // Helper function for {@link module:engine/model/documentselection~DocumentSelection#_updateAttributes}.
  592. //
  593. // 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`.
  594. //
  595. // @param {module:engine/model/item~Item|null} node
  596. // @returns {Boolean}
  597. function getAttrsIfCharacter( node ) {
  598. if ( node instanceof TextProxy || node instanceof Text ) {
  599. return node.getAttributes();
  600. }
  601. return null;
  602. }
  603. // Removes selection attributes from element which is not empty anymore.
  604. function clearAttributesStoredInElement( changes, batch, document ) {
  605. // Batch may not be passed to the document#change event in some tests.
  606. // See https://github.com/ckeditor/ckeditor5-engine/issues/1001#issuecomment-314202352
  607. // Ignore also transparent batches because they are... transparent.
  608. if ( !batch || batch.type == 'transparent' ) {
  609. return;
  610. }
  611. const changeParent = changes.range && changes.range.start.parent;
  612. // `changes.range` is not set in case of rename, root and marker operations.
  613. // None of them may lead to the element becoming non-empty.
  614. if ( !changeParent || changeParent.isEmpty ) {
  615. return;
  616. }
  617. document.enqueueChanges( () => {
  618. const storedAttributes = Array.from( changeParent.getAttributeKeys() ).filter( key => key.startsWith( storePrefix ) );
  619. for ( const key of storedAttributes ) {
  620. batch.removeAttribute( key, changeParent );
  621. }
  622. } );
  623. }