selection.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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/selection
  7. */
  8. import Position from './position';
  9. import Element from './element';
  10. import Range from './range';
  11. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  12. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  13. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  14. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  15. /**
  16. * `Selection` is a group of {@link module:engine/model/range~Range ranges} which has a direction specified by
  17. * {@link module:engine/model/selection~Selection#anchor anchor} and {@link module:engine/model/selection~Selection#focus focus}.
  18. * Additionally, `Selection` may have it's own attributes.
  19. *
  20. * @mixes {module:utils/emittermixin~EmitterMixin}
  21. */
  22. export default class Selection {
  23. /**
  24. * Creates new selection instance.
  25. *
  26. * @param {Iterable.<module:engine/view/range~Range>} [ranges] An optional iterable object of ranges to set.
  27. * @param {Boolean} [isLastBackward] An optional flag describing if last added range was selected forward - from start to end
  28. * (`false`) or backward - from end to start (`true`). Defaults to `false`.
  29. */
  30. constructor( ranges, isLastBackward ) {
  31. /**
  32. * Specifies whether the last added range was added as a backward or forward range.
  33. *
  34. * @private
  35. * @type {Boolean}
  36. */
  37. this._lastRangeBackward = false;
  38. /**
  39. * Stores selection ranges.
  40. *
  41. * @protected
  42. * @type {Array.<module:engine/model/range~Range>}
  43. */
  44. this._ranges = [];
  45. /**
  46. * List of attributes set on current selection.
  47. *
  48. * @protected
  49. * @type {Map.<String,*>}
  50. */
  51. this._attrs = new Map();
  52. if ( ranges ) {
  53. this._setRanges( ranges, isLastBackward );
  54. }
  55. }
  56. /**
  57. * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
  58. * Together with {@link #focus} they define the direction of selection, which is important
  59. * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
  60. * {@link module:engine/model/range~Range#end end} position of the most recently added range.
  61. *
  62. * Is set to `null` if there are no ranges in selection.
  63. *
  64. * @see #focus
  65. * @readonly
  66. * @type {module:engine/model/position~Position|null}
  67. */
  68. get anchor() {
  69. if ( this._ranges.length > 0 ) {
  70. const range = this._ranges[ this._ranges.length - 1 ];
  71. return this._lastRangeBackward ? range.end : range.start;
  72. }
  73. return null;
  74. }
  75. /**
  76. * Selection focus. Focus is a position where the selection ends.
  77. *
  78. * Is set to `null` if there are no ranges in selection.
  79. *
  80. * @see #anchor
  81. * @readonly
  82. * @type {module:engine/model/position~Position|null}
  83. */
  84. get focus() {
  85. if ( this._ranges.length > 0 ) {
  86. const range = this._ranges[ this._ranges.length - 1 ];
  87. return this._lastRangeBackward ? range.start : range.end;
  88. }
  89. return null;
  90. }
  91. /**
  92. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  93. * collapsed.
  94. *
  95. * @readonly
  96. * @type {Boolean}
  97. */
  98. get isCollapsed() {
  99. const length = this._ranges.length;
  100. if ( length === 1 ) {
  101. return this._ranges[ 0 ].isCollapsed;
  102. } else {
  103. return false;
  104. }
  105. }
  106. /**
  107. * Returns number of ranges in selection.
  108. *
  109. * @readonly
  110. * @type {Number}
  111. */
  112. get rangeCount() {
  113. return this._ranges.length;
  114. }
  115. /**
  116. * Specifies whether the {@link #focus}
  117. * precedes {@link #anchor}.
  118. *
  119. * @readonly
  120. * @type {Boolean}
  121. */
  122. get isBackward() {
  123. return !this.isCollapsed && this._lastRangeBackward;
  124. }
  125. /**
  126. * Checks whether this selection is equal to given selection. Selections are equal if they have same directions,
  127. * same number of ranges and all ranges from one selection equal to a range from other selection.
  128. *
  129. * @param {module:engine/model/selection~Selection} otherSelection Selection to compare with.
  130. * @returns {Boolean} `true` if selections are equal, `false` otherwise.
  131. */
  132. isEqual( otherSelection ) {
  133. if ( this.rangeCount != otherSelection.rangeCount ) {
  134. return false;
  135. } else if ( this.rangeCount === 0 ) {
  136. return true;
  137. }
  138. if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
  139. return false;
  140. }
  141. for ( const thisRange of this._ranges ) {
  142. let found = false;
  143. for ( const otherRange of otherSelection._ranges ) {
  144. if ( thisRange.isEqual( otherRange ) ) {
  145. found = true;
  146. break;
  147. }
  148. }
  149. if ( !found ) {
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. /**
  156. * Returns an iterable that iterates over copies of selection ranges.
  157. *
  158. * @returns {Iterable.<module:engine/model/range~Range>}
  159. */
  160. * getRanges() {
  161. for ( const range of this._ranges ) {
  162. yield Range.createFromRange( range );
  163. }
  164. }
  165. /**
  166. * Returns a copy of the first range in the selection.
  167. * First range is the one which {@link module:engine/model/range~Range#start start} position
  168. * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
  169. * (not to confuse with the first range added to the selection).
  170. *
  171. * Returns `null` if there are no ranges in selection.
  172. *
  173. * @returns {module:engine/model/range~Range|null}
  174. */
  175. getFirstRange() {
  176. let first = null;
  177. for ( const range of this._ranges ) {
  178. if ( !first || range.start.isBefore( first.start ) ) {
  179. first = range;
  180. }
  181. }
  182. return first ? Range.createFromRange( first ) : null;
  183. }
  184. /**
  185. * Returns a copy of the last range in the selection.
  186. * Last range is the one which {@link module:engine/model/range~Range#end end} position
  187. * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
  188. * recently added to the selection).
  189. *
  190. * Returns `null` if there are no ranges in selection.
  191. *
  192. * @returns {module:engine/model/range~Range|null}
  193. */
  194. getLastRange() {
  195. let last = null;
  196. for ( const range of this._ranges ) {
  197. if ( !last || range.end.isAfter( last.end ) ) {
  198. last = range;
  199. }
  200. }
  201. return last ? Range.createFromRange( last ) : null;
  202. }
  203. /**
  204. * Returns the first position in the selection.
  205. * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
  206. * any other position in the selection.
  207. *
  208. * Returns `null` if there are no ranges in selection.
  209. *
  210. * @returns {module:engine/model/position~Position|null}
  211. */
  212. getFirstPosition() {
  213. const first = this.getFirstRange();
  214. return first ? Position.createFromPosition( first.start ) : null;
  215. }
  216. /**
  217. * Returns the last position in the selection.
  218. * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
  219. * any other position in the selection.
  220. *
  221. * Returns `null` if there are no ranges in selection.
  222. *
  223. * @returns {module:engine/model/position~Position|null}
  224. */
  225. getLastPosition() {
  226. const lastRange = this.getLastRange();
  227. return lastRange ? Position.createFromPosition( lastRange.end ) : null;
  228. }
  229. /**
  230. * Sets this selection's ranges and direction to the specified location based on the given
  231. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  232. * {@link module:engine/model/element~Element element}, {@link module:engine/model/position~Position position},
  233. * {@link module:engine/model/range~Range range}, an iterable of {@link module:engine/model/range~Range ranges} or null.
  234. *
  235. * // Sets ranges from the given range.
  236. * const range = new Range( start, end );
  237. * selection.setTo( range, isBackwardSelection );
  238. *
  239. * // Sets ranges from the iterable of ranges.
  240. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  241. * selection.setTo( range, isBackwardSelection );
  242. *
  243. * // Sets ranges from the other selection.
  244. * const otherSelection = new Selection();
  245. * selection.setTo( otherSelection );
  246. *
  247. * // Sets ranges from the given document selection's ranges.
  248. * const documentSelection = new DocumentSelection( doc );
  249. * selection.setTo( documentSelection );
  250. *
  251. * // Sets range at the given position.
  252. * const position = new Position( root, path );
  253. * selection.setTo( position );
  254. *
  255. * // Sets range at the given element.
  256. * const paragraph = writer.createElement( 'paragraph' );
  257. * selection.setTo( paragraph, offset );
  258. *
  259. * // Removes all ranges.
  260. * selection.setTo( null );
  261. *
  262. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  263. * module:engine/model/position~Position|module:engine/model/element~Element|
  264. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range|null} selectable
  265. * @param {Boolean|Number|'before'|'end'|'after'} [backwardSelectionOrOffset]
  266. */
  267. setTo( selectable, backwardSelectionOrOffset ) {
  268. if ( selectable === null ) {
  269. this._setRanges( [] );
  270. } else if ( selectable instanceof Selection ) {
  271. this._setRanges( selectable.getRanges(), selectable.isBackward );
  272. } else if ( selectable && selectable._selection instanceof Selection ) {
  273. // We assume that the selectable is a DocumentSelection.
  274. // It can't be imported here, because it would lead to circular imports.
  275. this._setRanges( selectable.getRanges(), selectable.isBackward );
  276. } else if ( selectable instanceof Range ) {
  277. this._setRanges( [ selectable ], backwardSelectionOrOffset );
  278. } else if ( selectable instanceof Position ) {
  279. this._setRanges( [ new Range( selectable ) ] );
  280. } else if ( selectable instanceof Element ) {
  281. this._setRanges( [ Range.createCollapsedAt( selectable, backwardSelectionOrOffset ) ] );
  282. } else if ( isIterable( selectable ) ) {
  283. // We assume that the selectable is an iterable of ranges.
  284. this._setRanges( selectable, backwardSelectionOrOffset );
  285. } else {
  286. /**
  287. * Cannot set selection to given place.
  288. *
  289. * @error model-selection-setTo-not-selectable
  290. */
  291. throw new CKEditorError( 'model-selection-setTo-not-selectable: Cannot set selection to given place.' );
  292. }
  293. }
  294. /**
  295. * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
  296. * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
  297. * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made.
  298. *
  299. * @protected
  300. * @fires change:range
  301. * @param {Iterable.<module:engine/model/range~Range>} newRanges Ranges to set.
  302. * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end (`false`)
  303. * or backward - from end to start (`true`).
  304. */
  305. _setRanges( newRanges, isLastBackward = false ) {
  306. newRanges = Array.from( newRanges );
  307. // Check whether there is any range in new ranges set that is different than all already added ranges.
  308. const anyNewRange = newRanges.some( newRange => {
  309. if ( !( newRange instanceof Range ) ) {
  310. throw new CKEditorError( 'model-selection-added-not-range: Trying to add an object that is not an instance of Range.' );
  311. }
  312. return this._ranges.every( oldRange => {
  313. return !oldRange.isEqual( newRange );
  314. } );
  315. } );
  316. // Don't do anything if nothing changed.
  317. if ( newRanges.length === this._ranges.length && !anyNewRange ) {
  318. return;
  319. }
  320. this._removeAllRanges();
  321. for ( const range of newRanges ) {
  322. this._pushRange( range );
  323. }
  324. this._lastRangeBackward = !!isLastBackward;
  325. this.fire( 'change:range', { directChange: true } );
  326. }
  327. /**
  328. * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
  329. *
  330. * The location can be specified in the same form as {@link module:engine/model/position~Position.createAt} parameters.
  331. *
  332. * @fires change:range
  333. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  334. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  335. * first parameter is a {@link module:engine/model/item~Item model item}.
  336. */
  337. setFocus( itemOrPosition, offset ) {
  338. if ( this.anchor === null ) {
  339. /**
  340. * Cannot set selection focus if there are no ranges in selection.
  341. *
  342. * @error model-selection-setFocus-no-ranges
  343. */
  344. throw new CKEditorError(
  345. 'model-selection-setFocus-no-ranges: Cannot set selection focus if there are no ranges in selection.'
  346. );
  347. }
  348. const newFocus = Position.createAt( itemOrPosition, offset );
  349. if ( newFocus.compareWith( this.focus ) == 'same' ) {
  350. return;
  351. }
  352. const anchor = this.anchor;
  353. if ( this._ranges.length ) {
  354. this._popRange();
  355. }
  356. if ( newFocus.compareWith( anchor ) == 'before' ) {
  357. this._pushRange( new Range( newFocus, anchor ) );
  358. this._lastRangeBackward = true;
  359. } else {
  360. this._pushRange( new Range( anchor, newFocus ) );
  361. this._lastRangeBackward = false;
  362. }
  363. this.fire( 'change:range', { directChange: true } );
  364. }
  365. /**
  366. * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
  367. *
  368. * @param {String} key Key of attribute to look for.
  369. * @returns {*} Attribute value or `undefined`.
  370. */
  371. getAttribute( key ) {
  372. return this._attrs.get( key );
  373. }
  374. /**
  375. * Returns iterable that iterates over this selection's attributes.
  376. *
  377. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  378. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  379. *
  380. * @returns {Iterable.<*>}
  381. */
  382. getAttributes() {
  383. return this._attrs.entries();
  384. }
  385. /**
  386. * Returns iterable that iterates over this selection's attribute keys.
  387. *
  388. * @returns {Iterable.<String>}
  389. */
  390. getAttributeKeys() {
  391. return this._attrs.keys();
  392. }
  393. /**
  394. * Checks if the selection has an attribute for given key.
  395. *
  396. * @param {String} key Key of attribute to check.
  397. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  398. */
  399. hasAttribute( key ) {
  400. return this._attrs.has( key );
  401. }
  402. /**
  403. * Removes an attribute with given key from the selection.
  404. *
  405. * If given attribute was set on the selection, fires the {@link #event:change} event with
  406. * removed attribute key.
  407. *
  408. * @fires change:attribute
  409. * @param {String} key Key of attribute to remove.
  410. */
  411. removeAttribute( key ) {
  412. if ( this.hasAttribute( key ) ) {
  413. this._attrs.delete( key );
  414. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  415. }
  416. }
  417. /**
  418. * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
  419. *
  420. * If the attribute value has changed, fires the {@link #event:change} event with
  421. * the attribute key.
  422. *
  423. * @fires change:attribute
  424. * @param {String} key Key of attribute to set.
  425. * @param {*} value Attribute value.
  426. */
  427. setAttribute( key, value ) {
  428. if ( this.getAttribute( key ) !== value ) {
  429. this._attrs.set( key, value );
  430. this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
  431. }
  432. }
  433. /**
  434. * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
  435. * one range in the selection, and that range contains exactly one element.
  436. * Returns `null` if there is no selected element.
  437. *
  438. * @returns {module:engine/model/element~Element|null}
  439. */
  440. getSelectedElement() {
  441. if ( this.rangeCount !== 1 ) {
  442. return null;
  443. }
  444. const range = this.getFirstRange();
  445. const nodeAfterStart = range.start.nodeAfter;
  446. const nodeBeforeEnd = range.end.nodeBefore;
  447. return ( nodeAfterStart instanceof Element && nodeAfterStart == nodeBeforeEnd ) ? nodeAfterStart : null;
  448. }
  449. /**
  450. * Gets elements of type "block" touched by the selection.
  451. *
  452. * This method's result can be used for example to apply block styling to all blocks covered by this selection.
  453. *
  454. * **Note:** `getSelectedBlocks()` always returns the deepest block.
  455. *
  456. * In this case the function will return exactly all 3 paragraphs:
  457. *
  458. * <paragraph>[a</paragraph>
  459. * <quote>
  460. * <paragraph>b</paragraph>
  461. * </quote>
  462. * <paragraph>c]d</paragraph>
  463. *
  464. * In this case the paragraph will also be returned, despite the collapsed selection:
  465. *
  466. * <paragraph>[]a</paragraph>
  467. *
  468. * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
  469. * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
  470. *
  471. * <paragraph>[a</paragraph>
  472. * <paragraph>b</paragraph>
  473. * <paragraph>]c</paragraph> // this block will not be returned
  474. *
  475. * @returns {Iterable.<module:engine/model/element~Element>}
  476. */
  477. * getSelectedBlocks() {
  478. const visited = new WeakSet();
  479. for ( const range of this.getRanges() ) {
  480. const startBlock = getParentBlock( range.start, visited );
  481. if ( startBlock ) {
  482. yield startBlock;
  483. }
  484. for ( const value of range.getWalker() ) {
  485. if ( value.type == 'elementEnd' && isUnvisitedBlockContainer( value.item, visited ) ) {
  486. yield value.item;
  487. }
  488. }
  489. const endBlock = getParentBlock( range.end, visited );
  490. // #984. Don't return the end block if the range ends right at its beginning.
  491. if ( endBlock && !range.end.isTouching( Position.createAt( endBlock ) ) ) {
  492. yield endBlock;
  493. }
  494. }
  495. }
  496. /**
  497. * Checks whether the selection contains the entire content of the given element. This means that selection must start
  498. * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
  499. * touching the element's end.
  500. *
  501. * By default, this method will check whether the entire content of the selection's current root is selected.
  502. * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
  503. *
  504. * @param {module:engine/model/element~Element} [element=this.anchor.root]
  505. * @returns {Boolean}
  506. */
  507. containsEntireContent( element = this.anchor.root ) {
  508. const limitStartPosition = Position.createAt( element );
  509. const limitEndPosition = Position.createAt( element, 'end' );
  510. return limitStartPosition.isTouching( this.getFirstPosition() ) &&
  511. limitEndPosition.isTouching( this.getLastPosition() );
  512. }
  513. /**
  514. * Creates and returns an instance of `Selection` that is a clone of given selection, meaning that it has same
  515. * ranges and same direction as this selection.
  516. *
  517. * @params {module:engine/model/selection~Selection} otherSelection Selection to be cloned.
  518. * @returns {module:engine/model/selection~Selection} `Selection` instance that is a clone of given selection.
  519. */
  520. static createFromSelection( otherSelection ) {
  521. const selection = new this();
  522. selection.setTo( otherSelection );
  523. return selection;
  524. }
  525. /**
  526. * Adds given range to internal {@link #_ranges ranges array}. Throws an error
  527. * if given range is intersecting with any range that is already stored in this selection.
  528. *
  529. * @protected
  530. * @param {module:engine/model/range~Range} range Range to add.
  531. */
  532. _pushRange( range ) {
  533. this._checkRange( range );
  534. this._ranges.push( Range.createFromRange( range ) );
  535. }
  536. /**
  537. * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
  538. *
  539. * @protected
  540. * @param {module:engine/model/range~Range} range Range to check.
  541. */
  542. _checkRange( range ) {
  543. for ( let i = 0; i < this._ranges.length; i++ ) {
  544. if ( range.isIntersecting( this._ranges[ i ] ) ) {
  545. /**
  546. * Trying to add a range that intersects with another range from selection.
  547. *
  548. * @error model-selection-range-intersects
  549. * @param {module:engine/model/range~Range} addedRange Range that was added to the selection.
  550. * @param {module:engine/model/range~Range} intersectingRange Range from selection that intersects with `addedRange`.
  551. */
  552. throw new CKEditorError(
  553. 'model-selection-range-intersects: Trying to add a range that intersects with another range from selection.',
  554. { addedRange: range, intersectingRange: this._ranges[ i ] }
  555. );
  556. }
  557. }
  558. }
  559. /**
  560. * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
  561. * ensure proper ranges removal.
  562. *
  563. * @protected
  564. */
  565. _removeAllRanges() {
  566. while ( this._ranges.length > 0 ) {
  567. this._popRange();
  568. }
  569. }
  570. /**
  571. * Removes most recently added range from the selection.
  572. *
  573. * @protected
  574. */
  575. _popRange() {
  576. this._ranges.pop();
  577. }
  578. /**
  579. * @event change
  580. */
  581. /**
  582. * Fired whenever selection ranges are changed.
  583. *
  584. * @event change:range
  585. * @param {Boolean} directChange Specifies whether the range change was caused by direct usage of `Selection` API (`true`)
  586. * or by changes done to {@link module:engine/model/document~Document model document}
  587. * using {@link module:engine/model/batch~Batch Batch} API (`false`).
  588. */
  589. /**
  590. * Fired whenever selection attributes are changed.
  591. *
  592. * @event change:attribute
  593. * @param {Boolean} directChange Specifies whether the attributes changed by direct usage of the Selection API (`true`)
  594. * or by changes done to the {@link module:engine/model/document~Document model document}
  595. * using the {@link module:engine/model/batch~Batch Batch} API (`false`).
  596. * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
  597. */
  598. }
  599. mix( Selection, EmitterMixin );
  600. // Checks whether the given element extends $block in the schema and has a parent (is not a root).
  601. // Marks it as already visited.
  602. function isUnvisitedBlockContainer( element, visited ) {
  603. if ( visited.has( element ) ) {
  604. return false;
  605. }
  606. visited.add( element );
  607. return element.document.model.schema.isBlock( element ) && element.parent;
  608. }
  609. // Finds the lowest element in position's ancestors which is a block.
  610. // Marks all ancestors as already visited to not include any of them later on.
  611. function getParentBlock( position, visited ) {
  612. const ancestors = position.parent.getAncestors( { parentFirst: true, includeSelf: true } );
  613. const block = ancestors.find( element => isUnvisitedBlockContainer( element, visited ) );
  614. // Mark all ancestors of this position's parent, because find() might've stopped early and
  615. // the found block may be a child of another block.
  616. ancestors.forEach( element => visited.add( element ) );
  617. return block;
  618. }