documentselection.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/model/documentselection
  7. */
  8. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  9. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  10. import Selection from './selection';
  11. import LiveRange from './liverange';
  12. import Text from './text';
  13. import TextProxy from './textproxy';
  14. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  15. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  16. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  17. import uid from '@ckeditor/ckeditor5-utils/src/uid';
  18. const storePrefix = 'selection:';
  19. /**
  20. * `DocumentSelection` is a special selection which is used as the
  21. * {@link module:engine/model/document~Document#selection document's selection}.
  22. * There can be only one instance of `DocumentSelection` per document.
  23. *
  24. * Document selection can only be changed by using the {@link module:engine/model/writer~Writer} instance
  25. * inside the {@link module:engine/model/model~Model#change `change()`} block, as it provides a secure way to modify model.
  26. *
  27. * `DocumentSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
  28. * to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
  29. *
  30. * Differences between {@link module:engine/model/selection~Selection} and `DocumentSelection` are:
  31. * * there is always a range in `DocumentSelection` - even if no ranges were added there is a "default range"
  32. * present in the selection,
  33. * * ranges added to this selection updates automatically when the document changes,
  34. * * attributes of `DocumentSelection` are updated automatically according to selection ranges.
  35. *
  36. * Since `DocumentSelection` uses {@link module:engine/model/liverange~LiveRange live ranges}
  37. * and is updated when {@link module:engine/model/document~Document document}
  38. * changes, it cannot be set on {@link module:engine/model/node~Node nodes}
  39. * that are inside {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
  40. * If you need to represent a selection in document fragment,
  41. * use {@link module:engine/model/selection~Selection Selection class} instead.
  42. *
  43. * @mixes module:utils/emittermixin~EmitterMixin
  44. */
  45. export default class DocumentSelection {
  46. /**
  47. * Creates an empty live selection for given {@link module:engine/model/document~Document}.
  48. *
  49. * @param {module:engine/model/document~Document} doc Document which owns this selection.
  50. */
  51. constructor( doc ) {
  52. /**
  53. * Selection used internally by that class (`DocumentSelection` is a proxy to that selection).
  54. *
  55. * @protected
  56. */
  57. this._selection = new LiveSelection( doc );
  58. this._selection.delegate( 'change:range' ).to( this );
  59. this._selection.delegate( 'change:attribute' ).to( this );
  60. }
  61. /**
  62. * Returns whether the selection is collapsed. Selection is collapsed when there is exactly one range which is
  63. * collapsed.
  64. *
  65. * @readonly
  66. * @type {Boolean}
  67. */
  68. get isCollapsed() {
  69. return this._selection.isCollapsed;
  70. }
  71. /**
  72. * Selection anchor. Anchor may be described as a position where the most recent part of the selection starts.
  73. * Together with {@link #focus} they define the direction of selection, which is important
  74. * when expanding/shrinking selection. Anchor is always {@link module:engine/model/range~Range#start start} or
  75. * {@link module:engine/model/range~Range#end end} position of the most recently added range.
  76. *
  77. * Is set to `null` if there are no ranges in selection.
  78. *
  79. * @see #focus
  80. * @readonly
  81. * @type {module:engine/model/position~Position|null}
  82. */
  83. get anchor() {
  84. return this._selection.anchor;
  85. }
  86. /**
  87. * Selection focus. Focus is a position where the selection ends.
  88. *
  89. * Is set to `null` if there are no ranges in selection.
  90. *
  91. * @see #anchor
  92. * @readonly
  93. * @type {module:engine/model/position~Position|null}
  94. */
  95. get focus() {
  96. return this._selection.focus;
  97. }
  98. /**
  99. * Returns number of ranges in selection.
  100. *
  101. * @readonly
  102. * @type {Number}
  103. */
  104. get rangeCount() {
  105. return this._selection.rangeCount;
  106. }
  107. /**
  108. * Describes whether `Documentselection` has own range(s) set, or if it is defaulted to
  109. * {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
  110. *
  111. * @readonly
  112. * @type {Boolean}
  113. */
  114. get hasOwnRange() {
  115. return this._selection.hasOwnRange;
  116. }
  117. /**
  118. * Specifies whether the {@link #focus}
  119. * precedes {@link #anchor}.
  120. *
  121. * @readonly
  122. * @type {Boolean}
  123. */
  124. get isBackward() {
  125. return this._selection.isBackward;
  126. }
  127. /**
  128. * Describes whether the gravity is overridden (using {@link module:engine/model/writer~Writer#overrideSelectionGravity}) or not.
  129. *
  130. * Note that the gravity remains overridden as long as will not be restored the same number of times as it was overridden.
  131. *
  132. * @readonly
  133. * @returns {Boolean}
  134. */
  135. get isGravityOverridden() {
  136. return this._selection.isGravityOverridden;
  137. }
  138. /**
  139. * A collection of selection markers.
  140. * Marker is a selection marker when selection range is inside the marker range.
  141. *
  142. * @readonly
  143. * @type {module:utils/collection~Collection.<module:engine/model/markercollection~Marker>}
  144. */
  145. get markers() {
  146. return this._selection.markers;
  147. }
  148. /**
  149. * Used for the compatibility with the {@link module:engine/model/selection~Selection#isEqual} method.
  150. *
  151. * @protected
  152. */
  153. get _ranges() {
  154. return this._selection._ranges;
  155. }
  156. /**
  157. * Returns an iterable that iterates over copies of selection ranges.
  158. *
  159. * @returns {Iterable.<module:engine/model/range~Range>}
  160. */
  161. getRanges() {
  162. return this._selection.getRanges();
  163. }
  164. /**
  165. * Returns the first position in the selection.
  166. * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
  167. * any other position in the selection.
  168. *
  169. * Returns `null` if there are no ranges in selection.
  170. *
  171. * @returns {module:engine/model/position~Position|null}
  172. */
  173. getFirstPosition() {
  174. return this._selection.getFirstPosition();
  175. }
  176. /**
  177. * Returns the last position in the selection.
  178. * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
  179. * any other position in the selection.
  180. *
  181. * Returns `null` if there are no ranges in selection.
  182. *
  183. * @returns {module:engine/model/position~Position|null}
  184. */
  185. getLastPosition() {
  186. return this._selection.getLastPosition();
  187. }
  188. /**
  189. * Returns a copy of the first range in the selection.
  190. * First range is the one which {@link module:engine/model/range~Range#start start} position
  191. * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
  192. * (not to confuse with the first range added to the selection).
  193. *
  194. * Returns `null` if there are no ranges in selection.
  195. *
  196. * @returns {module:engine/model/range~Range|null}
  197. */
  198. getFirstRange() {
  199. return this._selection.getFirstRange();
  200. }
  201. /**
  202. * Returns a copy of the last range in the selection.
  203. * Last range is the one which {@link module:engine/model/range~Range#end end} position
  204. * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
  205. * recently added to the selection).
  206. *
  207. * Returns `null` if there are no ranges in selection.
  208. *
  209. * @returns {module:engine/model/range~Range|null}
  210. */
  211. getLastRange() {
  212. return this._selection.getLastRange();
  213. }
  214. /**
  215. * Gets elements of type "block" touched by the selection.
  216. *
  217. * This method's result can be used for example to apply block styling to all blocks covered by this selection.
  218. *
  219. * **Note:** `getSelectedBlocks()` always returns the deepest block.
  220. *
  221. * In this case the function will return exactly all 3 paragraphs:
  222. *
  223. * <paragraph>[a</paragraph>
  224. * <quote>
  225. * <paragraph>b</paragraph>
  226. * </quote>
  227. * <paragraph>c]d</paragraph>
  228. *
  229. * In this case the paragraph will also be returned, despite the collapsed selection:
  230. *
  231. * <paragraph>[]a</paragraph>
  232. *
  233. * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
  234. * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
  235. *
  236. * <paragraph>[a</paragraph>
  237. * <paragraph>b</paragraph>
  238. * <paragraph>]c</paragraph> // this block will not be returned
  239. *
  240. * @returns {Iterable.<module:engine/model/element~Element>}
  241. */
  242. getSelectedBlocks() {
  243. return this._selection.getSelectedBlocks();
  244. }
  245. /**
  246. * Returns blocks that aren't nested in other selected blocks.
  247. *
  248. * In this case the method will return blocks A, B and E because C & D are children of block B:
  249. *
  250. * [<blockA></blockA>
  251. * <blockB>
  252. * <blockC></blockC>
  253. * <blockD></blockD>
  254. * </blockB>
  255. * <blockE></blockE>]
  256. *
  257. * **Note:** To get all selected blocks use {@link #getSelectedBlocks `getSelectedBlocks()`}.
  258. *
  259. * @returns {Iterable.<module:engine/model/element~Element>}
  260. */
  261. getTopMostBlocks() {
  262. return this._selection.getTopMostBlocks();
  263. }
  264. /**
  265. * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
  266. * one range in the selection, and that range contains exactly one element.
  267. * Returns `null` if there is no selected element.
  268. *
  269. * @returns {module:engine/model/element~Element|null}
  270. */
  271. getSelectedElement() {
  272. return this._selection.getSelectedElement();
  273. }
  274. /**
  275. * Checks whether the selection contains the entire content of the given element. This means that selection must start
  276. * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
  277. * touching the element's end.
  278. *
  279. * By default, this method will check whether the entire content of the selection's current root is selected.
  280. * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
  281. *
  282. * @param {module:engine/model/element~Element} [element=this.anchor.root]
  283. * @returns {Boolean}
  284. */
  285. containsEntireContent( element ) {
  286. return this._selection.containsEntireContent( element );
  287. }
  288. /**
  289. * Unbinds all events previously bound by document selection.
  290. */
  291. destroy() {
  292. this._selection.destroy();
  293. }
  294. /**
  295. * Returns iterable that iterates over this selection's attribute keys.
  296. *
  297. * @returns {Iterable.<String>}
  298. */
  299. getAttributeKeys() {
  300. return this._selection.getAttributeKeys();
  301. }
  302. /**
  303. * Returns iterable that iterates over this selection's attributes.
  304. *
  305. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  306. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  307. *
  308. * @returns {Iterable.<*>}
  309. */
  310. getAttributes() {
  311. return this._selection.getAttributes();
  312. }
  313. /**
  314. * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
  315. *
  316. * @param {String} key Key of attribute to look for.
  317. * @returns {*} Attribute value or `undefined`.
  318. */
  319. getAttribute( key ) {
  320. return this._selection.getAttribute( key );
  321. }
  322. /**
  323. * Checks if the selection has an attribute for given key.
  324. *
  325. * @param {String} key Key of attribute to check.
  326. * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
  327. */
  328. hasAttribute( key ) {
  329. return this._selection.hasAttribute( key );
  330. }
  331. /**
  332. * Refreshes selection attributes and markers according to the current position in the model.
  333. */
  334. refresh() {
  335. this._selection._updateMarkers();
  336. this._selection._updateAttributes( false );
  337. }
  338. /**
  339. * Method verifies if the checked object belongs to a given a type. Type's name might be prefixed with a `model:` string,
  340. * for example `model:selection`. Type is a string which usually equal to a name of the class written in camelCase convention.
  341. * If the object is a class instance, which has a parent class with `is()` method, then type verification returns `true`
  342. * for any type match for an entire child-parent chain.
  343. *
  344. * const selection = new DocumentSelection( ... );
  345. *
  346. * selection.is( 'selection' ); // true
  347. * selection.is( 'model:selection' ); // true
  348. * selection.is( 'documentSelection' ); // true
  349. * selection.is( 'model:documentSelection' ); // true
  350. * selection.is( 'view:selection' ); // false
  351. * selection.is( 'node' ); // false
  352. * selection.is( 'model:node' ); // false
  353. * selection.is( 'element' ); // false
  354. *
  355. * Acceptable type for this class is `selection` and its prefixed version.
  356. *
  357. * See also: {@link module:engine/model/node~Node#is `Node#is()`}.
  358. *
  359. * @param {String} type
  360. * @returns {Boolean}
  361. */
  362. is( type ) {
  363. return type == 'selection' ||
  364. type == 'model:selection' ||
  365. type == 'documentSelection' ||
  366. type == 'model:documentSelection';
  367. }
  368. /**
  369. * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
  370. * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionFocus} method.
  371. *
  372. * The location can be specified in the same form as
  373. * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
  374. *
  375. * @see module:engine/model/writer~Writer#setSelectionFocus
  376. * @protected
  377. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  378. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  379. * first parameter is a {@link module:engine/model/item~Item model item}.
  380. */
  381. _setFocus( itemOrPosition, offset ) {
  382. this._selection.setFocus( itemOrPosition, offset );
  383. }
  384. /**
  385. * Sets this selection's ranges and direction to the specified location based on the given
  386. * {@link module:engine/model/selection~Selectable selectable}.
  387. * Should be used only within the {@link module:engine/model/writer~Writer#setSelection} method.
  388. *
  389. * @see module:engine/model/writer~Writer#setSelection
  390. * @protected
  391. * @param {module:engine/model/selection~Selectable} selectable
  392. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  393. * @param {Object} [options]
  394. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  395. */
  396. _setTo( selectable, placeOrOffset, options ) {
  397. this._selection.setTo( selectable, placeOrOffset, options );
  398. }
  399. /**
  400. * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
  401. * Should be used only within the {@link module:engine/model/writer~Writer#setSelectionAttribute} method.
  402. *
  403. * @see module:engine/model/writer~Writer#setSelectionAttribute
  404. * @protected
  405. * @param {String} key Key of the attribute to set.
  406. * @param {*} value Attribute value.
  407. */
  408. _setAttribute( key, value ) {
  409. this._selection.setAttribute( key, value );
  410. }
  411. /**
  412. * Removes an attribute with given key from the selection.
  413. * If the given attribute was set on the selection, fires the {@link module:engine/model/selection~Selection#event:change:range}
  414. * event with removed attribute key.
  415. * Should be used only within the {@link module:engine/model/writer~Writer#removeSelectionAttribute} method.
  416. *
  417. * @see module:engine/model/writer~Writer#removeSelectionAttribute
  418. * @protected
  419. * @param {String} key Key of the attribute to remove.
  420. */
  421. _removeAttribute( key ) {
  422. this._selection.removeAttribute( key );
  423. }
  424. /**
  425. * Returns an iterable that iterates through all selection attributes stored in current selection's parent.
  426. *
  427. * @protected
  428. * @returns {Iterable.<*>}
  429. */
  430. _getStoredAttributes() {
  431. return this._selection._getStoredAttributes();
  432. }
  433. /**
  434. * Temporarily changes the gravity of the selection from the left to the right.
  435. *
  436. * The gravity defines from which direction the selection inherits its attributes. If it's the default left
  437. * gravity, the selection (after being moved by the the user) inherits attributes from its left hand side.
  438. * This method allows to temporarily override this behavior by forcing the gravity to the right.
  439. *
  440. * It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
  441. * of the process.
  442. *
  443. * @see module:engine/model/writer~Writer#overrideSelectionGravity
  444. * @protected
  445. * @returns {String} The unique id which allows restoring the gravity.
  446. */
  447. _overrideGravity() {
  448. return this._selection.overrideGravity();
  449. }
  450. /**
  451. * Restores the {@link ~DocumentSelection#_overrideGravity overridden gravity}.
  452. *
  453. * Restoring the gravity is only possible using the unique identifier returned by
  454. * {@link ~DocumentSelection#_overrideGravity}. Note that the gravity remains overridden as long as won't be restored
  455. * the same number of times it was overridden.
  456. *
  457. * @see module:engine/model/writer~Writer#restoreSelectionGravity
  458. * @protected
  459. * @param {String} uid The unique id returned by {@link #_overrideGravity}.
  460. */
  461. _restoreGravity( uid ) {
  462. this._selection.restoreGravity( uid );
  463. }
  464. /**
  465. * Generates and returns an attribute key for selection attributes store, basing on original attribute key.
  466. *
  467. * @protected
  468. * @param {String} key Attribute key to convert.
  469. * @returns {String} Converted attribute key, applicable for selection store.
  470. */
  471. static _getStoreAttributeKey( key ) {
  472. return storePrefix + key;
  473. }
  474. /**
  475. * Checks whether the given attribute key is an attribute stored on an element.
  476. *
  477. * @protected
  478. * @param {String} key
  479. * @returns {Boolean}
  480. */
  481. static _isStoreAttributeKey( key ) {
  482. return key.startsWith( storePrefix );
  483. }
  484. }
  485. mix( DocumentSelection, EmitterMixin );
  486. /**
  487. * Fired when selection range(s) changed.
  488. *
  489. * @event change:range
  490. * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
  491. * to `true` which indicates that the selection change was caused by a direct use of selection's API.
  492. * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its position
  493. * was directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
  494. * changed because the structure of the model has been changed (which means an indirect change).
  495. * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
  496. * which mean that they are not updated once the document changes.
  497. */
  498. /**
  499. * Fired when selection attribute changed.
  500. *
  501. * @event change:attribute
  502. * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
  503. * to `true` which indicates that the selection change was caused by a direct use of selection's API.
  504. * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its attributes
  505. * were directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
  506. * changed in the model and its attributes were refreshed (which means an indirect change).
  507. * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
  508. * which mean that they are not updated once the document changes.
  509. * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
  510. */
  511. // `LiveSelection` is used internally by {@link module:engine/model/documentselection~DocumentSelection} and shouldn't be used directly.
  512. //
  513. // LiveSelection` is automatically updated upon changes in the {@link module:engine/model/document~Document document}
  514. // to always contain valid ranges. Its attributes are inherited from the text unless set explicitly.
  515. //
  516. // Differences between {@link module:engine/model/selection~Selection} and `LiveSelection` are:
  517. // * there is always a range in `LiveSelection` - even if no ranges were added there is a "default range"
  518. // present in the selection,
  519. // * ranges added to this selection updates automatically when the document changes,
  520. // * attributes of `LiveSelection` are updated automatically according to selection ranges.
  521. //
  522. // @extends module:engine/model/selection~Selection
  523. //
  524. class LiveSelection extends Selection {
  525. // Creates an empty live selection for given {@link module:engine/model/document~Document}.
  526. // @param {module:engine/model/document~Document} doc Document which owns this selection.
  527. constructor( doc ) {
  528. super();
  529. // List of selection markers.
  530. // Marker is a selection marker when selection range is inside the marker range.
  531. //
  532. // @type {module:utils/collection~Collection}
  533. this.markers = new Collection( { idProperty: 'name' } );
  534. // Document which owns this selection.
  535. //
  536. // @protected
  537. // @member {module:engine/model/model~Model}
  538. this._model = doc.model;
  539. // Document which owns this selection.
  540. //
  541. // @protected
  542. // @member {module:engine/model/document~Document}
  543. this._document = doc;
  544. // Keeps mapping of attribute name to priority with which the attribute got modified (added/changed/removed)
  545. // last time. Possible values of priority are: `'low'` and `'normal'`.
  546. //
  547. // Priorities are used by internal `LiveSelection` mechanisms. All attributes set using `LiveSelection`
  548. // attributes API are set with `'normal'` priority.
  549. //
  550. // @private
  551. // @member {Map} module:engine/model/liveselection~LiveSelection#_attributePriority
  552. this._attributePriority = new Map();
  553. // Contains data required to fix ranges which have been moved to the graveyard.
  554. // @private
  555. // @member {Array} module:engine/model/liveselection~LiveSelection#_fixGraveyardRangesData
  556. this._fixGraveyardRangesData = [];
  557. // Flag that informs whether the selection ranges have changed. It is changed on true when `LiveRange#change:range` event is fired.
  558. // @private
  559. // @member {Array} module:engine/model/liveselection~LiveSelection#_hasChangedRange
  560. this._hasChangedRange = false;
  561. // Each overriding gravity adds an UID to the set and each removal removes it.
  562. // Gravity is overridden when there's at least one UID in the set.
  563. // Gravity is restored when the set is empty.
  564. // This is to prevent conflicts when gravity is overridden by more than one feature at the same time.
  565. // @private
  566. // @type {Set}
  567. this._overriddenGravityRegister = new Set();
  568. // Ensure selection is correct after each operation.
  569. this.listenTo( this._model, 'applyOperation', ( evt, args ) => {
  570. const operation = args[ 0 ];
  571. if ( !operation.isDocumentOperation || operation.type == 'marker' || operation.type == 'rename' || operation.type == 'noop' ) {
  572. return;
  573. }
  574. while ( this._fixGraveyardRangesData.length ) {
  575. const { liveRange, sourcePosition } = this._fixGraveyardRangesData.shift();
  576. this._fixGraveyardSelection( liveRange, sourcePosition );
  577. }
  578. if ( this._hasChangedRange ) {
  579. this._hasChangedRange = false;
  580. this.fire( 'change:range', { directChange: false } );
  581. }
  582. }, { priority: 'lowest' } );
  583. // Ensure selection is correct and up to date after each range change.
  584. this.on( 'change:range', () => {
  585. for ( const range of this.getRanges() ) {
  586. if ( !this._document._validateSelectionRange( range ) ) {
  587. /**
  588. * Range from {@link module:engine/model/documentselection~DocumentSelection document selection}
  589. * starts or ends at incorrect position.
  590. *
  591. * @error document-selection-wrong-position
  592. * @param {module:engine/model/range~Range} range
  593. */
  594. throw new CKEditorError(
  595. 'document-selection-wrong-position: Range from document selection starts or ends at incorrect position.',
  596. this,
  597. { range }
  598. );
  599. }
  600. }
  601. } );
  602. // Update markers data stored by the selection after each marker change.
  603. this.listenTo( this._model.markers, 'update', () => this._updateMarkers() );
  604. // Ensure selection is up to date after each change block.
  605. this.listenTo( this._document, 'change', ( evt, batch ) => {
  606. clearAttributesStoredInElement( this._model, batch );
  607. } );
  608. }
  609. get isCollapsed() {
  610. const length = this._ranges.length;
  611. return length === 0 ? this._document._getDefaultRange().isCollapsed : super.isCollapsed;
  612. }
  613. get anchor() {
  614. return super.anchor || this._document._getDefaultRange().start;
  615. }
  616. get focus() {
  617. return super.focus || this._document._getDefaultRange().end;
  618. }
  619. get rangeCount() {
  620. return this._ranges.length ? this._ranges.length : 1;
  621. }
  622. // Describes whether `LiveSelection` has own range(s) set, or if it is defaulted to
  623. // {@link module:engine/model/document~Document#_getDefaultRange document's default range}.
  624. //
  625. // @readonly
  626. // @type {Boolean}
  627. get hasOwnRange() {
  628. return this._ranges.length > 0;
  629. }
  630. // When set to `true` then selection attributes on node before the caret won't be taken
  631. // into consideration while updating selection attributes.
  632. //
  633. // @protected
  634. // @type {Boolean}
  635. get isGravityOverridden() {
  636. return !!this._overriddenGravityRegister.size;
  637. }
  638. // Unbinds all events previously bound by live selection.
  639. destroy() {
  640. for ( let i = 0; i < this._ranges.length; i++ ) {
  641. this._ranges[ i ].detach();
  642. }
  643. this.stopListening();
  644. }
  645. * getRanges() {
  646. if ( this._ranges.length ) {
  647. yield* super.getRanges();
  648. } else {
  649. yield this._document._getDefaultRange();
  650. }
  651. }
  652. getFirstRange() {
  653. return super.getFirstRange() || this._document._getDefaultRange();
  654. }
  655. getLastRange() {
  656. return super.getLastRange() || this._document._getDefaultRange();
  657. }
  658. setTo( selectable, optionsOrPlaceOrOffset, options ) {
  659. super.setTo( selectable, optionsOrPlaceOrOffset, options );
  660. this._updateAttributes( true );
  661. }
  662. setFocus( itemOrPosition, offset ) {
  663. super.setFocus( itemOrPosition, offset );
  664. this._updateAttributes( true );
  665. }
  666. setAttribute( key, value ) {
  667. if ( this._setAttribute( key, value ) ) {
  668. // Fire event with exact data.
  669. const attributeKeys = [ key ];
  670. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  671. }
  672. }
  673. removeAttribute( key ) {
  674. if ( this._removeAttribute( key ) ) {
  675. // Fire event with exact data.
  676. const attributeKeys = [ key ];
  677. this.fire( 'change:attribute', { attributeKeys, directChange: true } );
  678. }
  679. }
  680. overrideGravity() {
  681. const overrideUid = uid();
  682. // Remember that another overriding has been requested. It will need to be removed
  683. // before the gravity is to be restored.
  684. this._overriddenGravityRegister.add( overrideUid );
  685. if ( this._overriddenGravityRegister.size === 1 ) {
  686. this._updateAttributes( true );
  687. }
  688. return overrideUid;
  689. }
  690. restoreGravity( uid ) {
  691. if ( !this._overriddenGravityRegister.has( uid ) ) {
  692. /**
  693. * Restoring gravity for an unknown UID is not possible. Make sure you are using a correct
  694. * UID obtained from the {@link module:engine/model/writer~Writer#overrideSelectionGravity} to restore.
  695. *
  696. * @error document-selection-gravity-wrong-restore
  697. * @param {String} uid The unique identifier returned by
  698. * {@link module:engine/model/documentselection~DocumentSelection#_overrideGravity}.
  699. */
  700. throw new CKEditorError(
  701. 'document-selection-gravity-wrong-restore: Attempting to restore the selection gravity for an unknown UID.',
  702. this,
  703. { uid }
  704. );
  705. }
  706. this._overriddenGravityRegister.delete( uid );
  707. // Restore gravity only when all overriding have been restored.
  708. if ( !this.isGravityOverridden ) {
  709. this._updateAttributes( true );
  710. }
  711. }
  712. _popRange() {
  713. this._ranges.pop().detach();
  714. }
  715. _pushRange( range ) {
  716. const liveRange = this._prepareRange( range );
  717. // `undefined` is returned when given `range` is in graveyard root.
  718. if ( liveRange ) {
  719. this._ranges.push( liveRange );
  720. }
  721. }
  722. // Prepares given range to be added to selection. Checks if it is correct,
  723. // converts it to {@link module:engine/model/liverange~LiveRange LiveRange}
  724. // and sets listeners listening to the range's change event.
  725. //
  726. // @private
  727. // @param {module:engine/model/range~Range} range
  728. _prepareRange( range ) {
  729. this._checkRange( range );
  730. if ( range.root == this._document.graveyard ) {
  731. // @if CK_DEBUG // console.warn( 'Trying to add a Range that is in the graveyard root. Range rejected.' );
  732. return;
  733. }
  734. const liveRange = LiveRange.fromRange( range );
  735. liveRange.on( 'change:range', ( evt, oldRange, data ) => {
  736. this._hasChangedRange = true;
  737. // If `LiveRange` is in whole moved to the graveyard, save necessary data. It will be fixed on `Model#applyOperation` event.
  738. if ( liveRange.root == this._document.graveyard ) {
  739. this._fixGraveyardRangesData.push( {
  740. liveRange,
  741. sourcePosition: data.deletionPosition
  742. } );
  743. }
  744. } );
  745. return liveRange;
  746. }
  747. _updateMarkers() {
  748. const markers = [];
  749. for ( const marker of this._model.markers ) {
  750. const markerRange = marker.getRange();
  751. for ( const selectionRange of this.getRanges() ) {
  752. if ( markerRange.containsRange( selectionRange, !selectionRange.isCollapsed ) ) {
  753. markers.push( marker );
  754. }
  755. }
  756. }
  757. for ( const marker of markers ) {
  758. if ( !this.markers.has( marker ) ) {
  759. this.markers.add( marker );
  760. }
  761. }
  762. for ( const marker of Array.from( this.markers ) ) {
  763. if ( !markers.includes( marker ) ) {
  764. this.markers.remove( marker );
  765. }
  766. }
  767. }
  768. // Updates this selection attributes according to its ranges and the {@link module:engine/model/document~Document model document}.
  769. //
  770. // @protected
  771. // @param {Boolean} clearAll
  772. // @fires change:attribute
  773. _updateAttributes( clearAll ) {
  774. const newAttributes = toMap( this._getSurroundingAttributes() );
  775. const oldAttributes = toMap( this.getAttributes() );
  776. if ( clearAll ) {
  777. // If `clearAll` remove all attributes and reset priorities.
  778. this._attributePriority = new Map();
  779. this._attrs = new Map();
  780. } else {
  781. // If not, remove only attributes added with `low` priority.
  782. for ( const [ key, priority ] of this._attributePriority ) {
  783. if ( priority == 'low' ) {
  784. this._attrs.delete( key );
  785. this._attributePriority.delete( key );
  786. }
  787. }
  788. }
  789. this._setAttributesTo( newAttributes );
  790. // Let's evaluate which attributes really changed.
  791. const changed = [];
  792. // First, loop through all attributes that are set on selection right now.
  793. // Check which of them are different than old attributes.
  794. for ( const [ newKey, newValue ] of this.getAttributes() ) {
  795. if ( !oldAttributes.has( newKey ) || oldAttributes.get( newKey ) !== newValue ) {
  796. changed.push( newKey );
  797. }
  798. }
  799. // Then, check which of old attributes got removed.
  800. for ( const [ oldKey ] of oldAttributes ) {
  801. if ( !this.hasAttribute( oldKey ) ) {
  802. changed.push( oldKey );
  803. }
  804. }
  805. // Fire event with exact data (fire only if anything changed).
  806. if ( changed.length > 0 ) {
  807. this.fire( 'change:attribute', { attributeKeys: changed, directChange: false } );
  808. }
  809. }
  810. // Internal method for setting `LiveSelection` attribute. Supports attribute priorities (through `directChange`
  811. // parameter).
  812. //
  813. // @private
  814. // @param {String} key Attribute key.
  815. // @param {*} value Attribute value.
  816. // @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  817. // is caused by `Batch` API.
  818. // @returns {Boolean} Whether value has changed.
  819. _setAttribute( key, value, directChange = true ) {
  820. const priority = directChange ? 'normal' : 'low';
  821. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  822. // Priority too low.
  823. return false;
  824. }
  825. const oldValue = super.getAttribute( key );
  826. // Don't do anything if value has not changed.
  827. if ( oldValue === value ) {
  828. return false;
  829. }
  830. this._attrs.set( key, value );
  831. // Update priorities map.
  832. this._attributePriority.set( key, priority );
  833. return true;
  834. }
  835. // Internal method for removing `LiveSelection` attribute. Supports attribute priorities (through `directChange`
  836. // parameter).
  837. //
  838. // NOTE: Even if attribute is not present in the selection but is provided to this method, it's priority will
  839. // be changed according to `directChange` parameter.
  840. //
  841. // @private
  842. // @param {String} key Attribute key.
  843. // @param {Boolean} [directChange=true] `true` if the change is caused by `Selection` API, `false` if change
  844. // is caused by `Batch` API.
  845. // @returns {Boolean} Whether attribute was removed. May not be true if such attributes didn't exist or the
  846. // existing attribute had higher priority.
  847. _removeAttribute( key, directChange = true ) {
  848. const priority = directChange ? 'normal' : 'low';
  849. if ( priority == 'low' && this._attributePriority.get( key ) == 'normal' ) {
  850. // Priority too low.
  851. return false;
  852. }
  853. // Update priorities map.
  854. this._attributePriority.set( key, priority );
  855. // Don't do anything if value has not changed.
  856. if ( !super.hasAttribute( key ) ) {
  857. return false;
  858. }
  859. this._attrs.delete( key );
  860. return true;
  861. }
  862. // Internal method for setting multiple `LiveSelection` attributes. Supports attribute priorities (through
  863. // `directChange` parameter).
  864. //
  865. // @private
  866. // @param {Map.<String,*>} attrs Iterable object containing attributes to be set.
  867. // @returns {Set.<String>} Changed attribute keys.
  868. _setAttributesTo( attrs ) {
  869. const changed = new Set();
  870. for ( const [ oldKey, oldValue ] of this.getAttributes() ) {
  871. // Do not remove attribute if attribute with same key and value is about to be set.
  872. if ( attrs.get( oldKey ) === oldValue ) {
  873. continue;
  874. }
  875. // All rest attributes will be removed so changed attributes won't change .
  876. this._removeAttribute( oldKey, false );
  877. }
  878. for ( const [ key, value ] of attrs ) {
  879. // Attribute may not be set because of attributes or because same key/value is already added.
  880. const gotAdded = this._setAttribute( key, value, false );
  881. if ( gotAdded ) {
  882. changed.add( key );
  883. }
  884. }
  885. return changed;
  886. }
  887. // Returns an iterable that iterates through all selection attributes stored in current selection's parent.
  888. //
  889. // @protected
  890. // @returns {Iterable.<*>}
  891. * _getStoredAttributes() {
  892. const selectionParent = this.getFirstPosition().parent;
  893. if ( this.isCollapsed && selectionParent.isEmpty ) {
  894. for ( const key of selectionParent.getAttributeKeys() ) {
  895. if ( key.startsWith( storePrefix ) ) {
  896. const realKey = key.substr( storePrefix.length );
  897. yield [ realKey, selectionParent.getAttribute( key ) ];
  898. }
  899. }
  900. }
  901. }
  902. // Checks model text nodes that are closest to the selection's first position and returns attributes of first
  903. // found element. If there are no text nodes in selection's first position parent, it returns selection
  904. // attributes stored in that parent.
  905. //
  906. // @private
  907. // @returns {Iterable.<*>} Collection of attributes.
  908. _getSurroundingAttributes() {
  909. const position = this.getFirstPosition();
  910. const schema = this._model.schema;
  911. let attrs = null;
  912. if ( !this.isCollapsed ) {
  913. // 1. If selection is a range...
  914. const range = this.getFirstRange();
  915. // ...look for a first character node in that range and take attributes from it.
  916. for ( const value of range ) {
  917. // If the item is an object, we don't want to get attributes from its children.
  918. if ( value.item.is( 'element' ) && schema.isObject( value.item ) ) {
  919. break;
  920. }
  921. if ( value.type == 'text' ) {
  922. attrs = value.item.getAttributes();
  923. break;
  924. }
  925. }
  926. } else {
  927. // 2. If the selection is a caret or the range does not contain a character node...
  928. const nodeBefore = position.textNode ? position.textNode : position.nodeBefore;
  929. const nodeAfter = position.textNode ? position.textNode : position.nodeAfter;
  930. // When gravity is overridden then don't take node before into consideration.
  931. if ( !this.isGravityOverridden ) {
  932. // ...look at the node before caret and take attributes from it if it is a character node.
  933. attrs = getAttrsIfCharacter( nodeBefore );
  934. }
  935. // 3. If not, look at the node after caret...
  936. if ( !attrs ) {
  937. attrs = getAttrsIfCharacter( nodeAfter );
  938. }
  939. // 4. If not, try to find the first character on the left, that is in the same node.
  940. // When gravity is overridden then don't take node before into consideration.
  941. if ( !this.isGravityOverridden && !attrs ) {
  942. let node = nodeBefore;
  943. while ( node && !attrs ) {
  944. node = node.previousSibling;
  945. attrs = getAttrsIfCharacter( node );
  946. }
  947. }
  948. // 5. If not found, try to find the first character on the right, that is in the same node.
  949. if ( !attrs ) {
  950. let node = nodeAfter;
  951. while ( node && !attrs ) {
  952. node = node.nextSibling;
  953. attrs = getAttrsIfCharacter( node );
  954. }
  955. }
  956. // 6. If not found, selection should retrieve attributes from parent.
  957. if ( !attrs ) {
  958. attrs = this._getStoredAttributes();
  959. }
  960. }
  961. return attrs;
  962. }
  963. // Fixes a selection range after it ends up in graveyard root.
  964. //
  965. // @private
  966. // @param {module:engine/model/liverange~LiveRange} liveRange The range from selection, that ended up in the graveyard root.
  967. // @param {module:engine/model/position~Position} removedRangeStart Start position of a range which was removed.
  968. _fixGraveyardSelection( liveRange, removedRangeStart ) {
  969. // The start of the removed range is the closest position to the `liveRange` - the original selection range.
  970. // This is a good candidate for a fixed selection range.
  971. const positionCandidate = removedRangeStart.clone();
  972. // Find a range that is a correct selection range and is closest to the start of removed range.
  973. const selectionRange = this._model.schema.getNearestSelectionRange( positionCandidate );
  974. // Remove the old selection range before preparing and adding new selection range. This order is important,
  975. // because new range, in some cases, may intersect with old range (it depends on `getNearestSelectionRange()` result).
  976. const index = this._ranges.indexOf( liveRange );
  977. this._ranges.splice( index, 1 );
  978. liveRange.detach();
  979. // If nearest valid selection range has been found - add it in the place of old range.
  980. if ( selectionRange ) {
  981. // Check the range, convert it to live range, bind events, etc.
  982. const newRange = this._prepareRange( selectionRange );
  983. // Add new range in the place of old range.
  984. this._ranges.splice( index, 0, newRange );
  985. }
  986. // If nearest valid selection range cannot be found - just removing the old range is fine.
  987. }
  988. }
  989. // Helper function for {@link module:engine/model/liveselection~LiveSelection#_updateAttributes}.
  990. //
  991. // 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`.
  992. //
  993. // @param {module:engine/model/item~Item|null} node
  994. // @returns {Boolean}
  995. function getAttrsIfCharacter( node ) {
  996. if ( node instanceof TextProxy || node instanceof Text ) {
  997. return node.getAttributes();
  998. }
  999. return null;
  1000. }
  1001. // Removes selection attributes from element which is not empty anymore.
  1002. //
  1003. // @private
  1004. // @param {module:engine/model/model~Model} model
  1005. // @param {module:engine/model/batch~Batch} batch
  1006. function clearAttributesStoredInElement( model, batch ) {
  1007. const differ = model.document.differ;
  1008. for ( const entry of differ.getChanges() ) {
  1009. if ( entry.type != 'insert' ) {
  1010. continue;
  1011. }
  1012. const changeParent = entry.position.parent;
  1013. const isNoLongerEmpty = entry.length === changeParent.maxOffset;
  1014. if ( isNoLongerEmpty ) {
  1015. model.enqueueChange( batch, writer => {
  1016. const storedAttributes = Array.from( changeParent.getAttributeKeys() )
  1017. .filter( key => key.startsWith( storePrefix ) );
  1018. for ( const key of storedAttributes ) {
  1019. writer.removeAttribute( key, changeParent );
  1020. }
  1021. } );
  1022. }
  1023. }
  1024. }