8
0

documentselection.js 22 KB

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