markercollection.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /**
  2. * @license Copyright (c) 2003-2020, 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/markercollection
  7. */
  8. import LiveRange from './liverange';
  9. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  12. /**
  13. * The collection of all {@link module:engine/model/markercollection~Marker markers} attached to the document.
  14. * It lets you {@link module:engine/model/markercollection~MarkerCollection#get get} markers or track them using
  15. * {@link module:engine/model/markercollection~MarkerCollection#event:update} event.
  16. *
  17. * To create, change or remove makers use {@link module:engine/model/writer~Writer model writers'} methods:
  18. * {@link module:engine/model/writer~Writer#addMarker} or {@link module:engine/model/writer~Writer#removeMarker}. Since
  19. * the writer is the only proper way to change the data model it is not possible to change markers directly using this
  20. * collection. All markers created by the writer will be automatically added to this collection.
  21. *
  22. * By default there is one marker collection available as {@link module:engine/model/model~Model#markers model property}.
  23. *
  24. * @see module:engine/model/markercollection~Marker
  25. */
  26. export default class MarkerCollection {
  27. /**
  28. * Creates a markers collection.
  29. */
  30. constructor() {
  31. /**
  32. * Stores {@link ~Marker markers} added to the collection.
  33. *
  34. * @private
  35. * @member {Map} #_markers
  36. */
  37. this._markers = new Map();
  38. }
  39. /**
  40. * Iterable interface.
  41. *
  42. * Iterates over all {@link ~Marker markers} added to the collection.
  43. *
  44. * @returns {Iterable}
  45. */
  46. [ Symbol.iterator ]() {
  47. return this._markers.values();
  48. }
  49. /**
  50. * Checks if marker with given `markerName` is in the collection.
  51. *
  52. * @param {String} markerName Marker name.
  53. * @returns {Boolean} `true` if marker with given `markerName` is in the collection, `false` otherwise.
  54. */
  55. has( markerName ) {
  56. return this._markers.has( markerName );
  57. }
  58. /**
  59. * Returns {@link ~Marker marker} with given `markerName`.
  60. *
  61. * @param {String} markerName Name of marker to get.
  62. * @returns {module:engine/model/markercollection~Marker|null} Marker with given name or `null` if such marker was
  63. * not added to the collection.
  64. */
  65. get( markerName ) {
  66. return this._markers.get( markerName ) || null;
  67. }
  68. /**
  69. * Creates and adds a {@link ~Marker marker} to the `MarkerCollection` with given name on given
  70. * {@link module:engine/model/range~Range range}.
  71. *
  72. * If `MarkerCollection` already had a marker with given name (or {@link ~Marker marker} was passed), the marker in
  73. * collection is updated and {@link module:engine/model/markercollection~MarkerCollection#event:update} event is fired
  74. * but only if there was a change (marker range or {@link module:engine/model/markercollection~Marker#managedUsingOperations}
  75. * flag has changed.
  76. *
  77. * @protected
  78. * @fires module:engine/model/markercollection~MarkerCollection#event:update
  79. * @param {String|module:engine/model/markercollection~Marker} markerOrName Name of marker to set or marker instance to update.
  80. * @param {module:engine/model/range~Range} range Marker range.
  81. * @param {Boolean} [managedUsingOperations=false] Specifies whether the marker is managed using operations.
  82. * @param {Boolean} [affectsData=false] Specifies whether the marker affects the data produced by the data pipeline
  83. * (is persisted in the editor's data).
  84. * @returns {module:engine/model/markercollection~Marker} `Marker` instance which was added or updated.
  85. */
  86. _set( markerOrName, range, managedUsingOperations = false, affectsData = false ) {
  87. const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
  88. if ( markerName.includes( ',' ) ) {
  89. throw new CKEditorError( 'markercollection-incorrect-marker-name: Marker name cannot contain "," character.', this );
  90. }
  91. const oldMarker = this._markers.get( markerName );
  92. if ( oldMarker ) {
  93. const oldRange = oldMarker.getRange();
  94. let hasChanged = false;
  95. if ( !oldRange.isEqual( range ) ) {
  96. oldMarker._attachLiveRange( LiveRange.fromRange( range ) );
  97. hasChanged = true;
  98. }
  99. if ( managedUsingOperations != oldMarker.managedUsingOperations ) {
  100. oldMarker._managedUsingOperations = managedUsingOperations;
  101. hasChanged = true;
  102. }
  103. if ( typeof affectsData === 'boolean' && affectsData != oldMarker.affectsData ) {
  104. oldMarker._affectsData = affectsData;
  105. hasChanged = true;
  106. }
  107. if ( hasChanged ) {
  108. this.fire( 'update:' + markerName, oldMarker, oldRange, range );
  109. }
  110. return oldMarker;
  111. }
  112. const liveRange = LiveRange.fromRange( range );
  113. const marker = new Marker( markerName, liveRange, managedUsingOperations, affectsData );
  114. this._markers.set( markerName, marker );
  115. this.fire( 'update:' + markerName, marker, null, range );
  116. return marker;
  117. }
  118. /**
  119. * Removes given {@link ~Marker marker} or a marker with given name from the `MarkerCollection`.
  120. *
  121. * @protected
  122. * @fires module:engine/model/markercollection~MarkerCollection#event:update
  123. * @param {String} markerOrName Marker or name of a marker to remove.
  124. * @returns {Boolean} `true` if marker was found and removed, `false` otherwise.
  125. */
  126. _remove( markerOrName ) {
  127. const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
  128. const oldMarker = this._markers.get( markerName );
  129. if ( oldMarker ) {
  130. this._markers.delete( markerName );
  131. this.fire( 'update:' + markerName, oldMarker, oldMarker.getRange(), null );
  132. this._destroyMarker( oldMarker );
  133. return true;
  134. }
  135. return false;
  136. }
  137. /**
  138. * Fires an {@link module:engine/model/markercollection~MarkerCollection#event:update} event for the given {@link ~Marker marker}
  139. * but does not change the marker. Useful to force {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher downcast
  140. * conversion} for the marker.
  141. *
  142. * @protected
  143. * @fires module:engine/model/markercollection~MarkerCollection#event:update
  144. * @param {String} markerOrName Marker or name of a marker to refresh.
  145. */
  146. _refresh( markerOrName ) {
  147. const markerName = markerOrName instanceof Marker ? markerOrName.name : markerOrName;
  148. const marker = this._markers.get( markerName );
  149. if ( !marker ) {
  150. throw new CKEditorError( 'markercollection-refresh-marker-not-exists: Marker with provided name does not exists.', this );
  151. }
  152. const range = marker.getRange();
  153. this.fire( 'update:' + markerName, marker, range, range, marker.managedUsingOperations, marker.affectsData );
  154. }
  155. /**
  156. * Returns iterator that iterates over all markers, which ranges contain given {@link module:engine/model/position~Position position}.
  157. *
  158. * @param {module:engine/model/position~Position} position
  159. * @returns {Iterable.<module:engine/model/markercollection~Marker>}
  160. */
  161. * getMarkersAtPosition( position ) {
  162. for ( const marker of this ) {
  163. if ( marker.getRange().containsPosition( position ) ) {
  164. yield marker;
  165. }
  166. }
  167. }
  168. /**
  169. * Returns iterator that iterates over all markers, which intersects with given {@link module:engine/model/range~Range range}.
  170. *
  171. * @param {module:engine/model/range~Range} range
  172. * @returns {Iterable.<module:engine/model/markercollection~Marker>}
  173. */
  174. * getMarkersIntersectingRange( range ) {
  175. for ( const marker of this ) {
  176. if ( marker.getRange().getIntersection( range ) !== null ) {
  177. yield marker;
  178. }
  179. }
  180. }
  181. /**
  182. * Destroys marker collection and all markers inside it.
  183. */
  184. destroy() {
  185. for ( const marker of this._markers.values() ) {
  186. this._destroyMarker( marker );
  187. }
  188. this._markers = null;
  189. this.stopListening();
  190. }
  191. /**
  192. * Iterates over all markers that starts with given `prefix`.
  193. *
  194. * const markerFooA = markersCollection.set( 'foo:a', rangeFooA );
  195. * const markerFooB = markersCollection.set( 'foo:b', rangeFooB );
  196. * const markerBarA = markersCollection.set( 'bar:a', rangeBarA );
  197. * const markerFooBarA = markersCollection.set( 'foobar:a', rangeFooBarA );
  198. * Array.from( markersCollection.getMarkersGroup( 'foo' ) ); // [ markerFooA, markerFooB ]
  199. * Array.from( markersCollection.getMarkersGroup( 'a' ) ); // []
  200. *
  201. * @param prefix
  202. * @returns {Iterable.<module:engine/model/markercollection~Marker>}
  203. */
  204. * getMarkersGroup( prefix ) {
  205. for ( const marker of this._markers.values() ) {
  206. if ( marker.name.startsWith( prefix + ':' ) ) {
  207. yield marker;
  208. }
  209. }
  210. }
  211. /**
  212. * Destroys the marker.
  213. *
  214. * @private
  215. * @param {module:engine/model/markercollection~Marker} marker Marker to destroy.
  216. */
  217. _destroyMarker( marker ) {
  218. marker.stopListening();
  219. marker._detachLiveRange();
  220. }
  221. /**
  222. * Fired whenever marker is added, updated or removed from `MarkerCollection`.
  223. *
  224. * @event update
  225. * @param {module:engine/model/markercollection~Marker} marker Updated Marker.
  226. * @param {module:engine/model/range~Range|null} oldRange Marker range before the update. When is not defined it
  227. * means that marker is just added.
  228. * @param {module:engine/model/range~Range|null} newRange Marker range after update. When is not defined it
  229. * means that marker is just removed.
  230. */
  231. }
  232. mix( MarkerCollection, EmitterMixin );
  233. /**
  234. * `Marker` is a continuous parts of model (like a range), is named and represent some kind of information about marked
  235. * part of model document. In contrary to {@link module:engine/model/node~Node nodes}, which are building blocks of
  236. * model document tree, markers are not stored directly in document tree but in
  237. * {@link module:engine/model/model~Model#markers model markers' collection}. Still, they are document data, by giving
  238. * additional meaning to the part of a model document between marker start and marker end.
  239. *
  240. * In this sense, markers are similar to adding and converting attributes on nodes. The difference is that attribute is
  241. * connected with a given node (e.g. a character is bold no matter if it gets moved or content around it changes).
  242. * Markers on the other hand are continuous ranges and are characterized by their start and end position. This means that
  243. * any character in the marker is marked by the marker. For example, if a character is moved outside of marker it stops being
  244. * "special" and the marker is shrunk. Similarly, when a character is moved into the marker from other place in document
  245. * model, it starts being "special" and the marker is enlarged.
  246. *
  247. * Another upside of markers is that finding marked part of document is fast and easy. Using attributes to mark some nodes
  248. * and then trying to find that part of document would require traversing whole document tree. Marker gives instant access
  249. * to the range which it is marking at the moment.
  250. *
  251. * Markers are built from a name and a range.
  252. *
  253. * Range of the marker is updated automatically when document changes, using
  254. * {@link module:engine/model/liverange~LiveRange live range} mechanism.
  255. *
  256. * Name is used to group and identify markers. Names have to be unique, but markers can be grouped by
  257. * using common prefixes, separated with `:`, for example: `user:john` or `search:3`. That's useful in term of creating
  258. * namespaces for custom elements (e.g. comments, highlights). You can use this prefixes in
  259. * {@link module:engine/model/markercollection~MarkerCollection#event:update} listeners to listen on changes in a group of markers.
  260. * For instance: `model.markers.on( 'update:user', callback );` will be called whenever any `user:*` markers changes.
  261. *
  262. * There are two types of markers.
  263. *
  264. * 1. Markers managed directly, without using operations. They are added directly by {@link module:engine/model/writer~Writer}
  265. * to the {@link module:engine/model/markercollection~MarkerCollection} without any additional mechanism. They can be used
  266. * as bookmarks or visual markers. They are great for showing results of the find, or select link when the focus is in the input.
  267. *
  268. * 1. Markers managed using operations. These markers are also stored in {@link module:engine/model/markercollection~MarkerCollection}
  269. * but changes in these markers is managed the same way all other changes in the model structure - using operations.
  270. * Therefore, they are handled in the undo stack and synchronized between clients if the collaboration plugin is enabled.
  271. * This type of markers is useful for solutions like spell checking or comments.
  272. *
  273. * Both type of them should be added / updated by {@link module:engine/model/writer~Writer#addMarker}
  274. * and removed by {@link module:engine/model/writer~Writer#removeMarker} methods.
  275. *
  276. * model.change( ( writer ) => {
  277. * const marker = writer.addMarker( name, { range, usingOperation: true } );
  278. *
  279. * // ...
  280. *
  281. * writer.removeMarker( marker );
  282. * } );
  283. *
  284. * See {@link module:engine/model/writer~Writer} to find more examples.
  285. *
  286. * Since markers need to track change in the document, for efficiency reasons, it is best to create and keep as little
  287. * markers as possible and remove them as soon as they are not needed anymore.
  288. *
  289. * Markers can be downcasted and upcasted.
  290. *
  291. * Markers downcast happens on {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker} and
  292. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarker} events.
  293. * Use {@link module:engine/conversion/downcasthelpers downcast converters} or attach a custom converter to mentioned events.
  294. * For {@link module:engine/controller/datacontroller~DataController data pipeline}, marker should be downcasted to an element.
  295. * Then, it can be upcasted back to a marker. Again, use {@link module:engine/conversion/upcasthelpers upcast converters} or
  296. * attach a custom converter to {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element}.
  297. *
  298. * `Marker` instances are created and destroyed only by {@link ~MarkerCollection MarkerCollection}.
  299. */
  300. class Marker {
  301. /**
  302. * Creates a marker instance.
  303. *
  304. * @param {String} name Marker name.
  305. * @param {module:engine/model/liverange~LiveRange} liveRange Range marked by the marker.
  306. * @param {Boolean} managedUsingOperations Specifies whether the marker is managed using operations.
  307. * @param {Boolean} affectsData Specifies whether the marker affects the data produced by the data pipeline
  308. * (is persisted in the editor's data).
  309. */
  310. constructor( name, liveRange, managedUsingOperations, affectsData ) {
  311. /**
  312. * Marker's name.
  313. *
  314. * @readonly
  315. * @type {String}
  316. */
  317. this.name = name;
  318. /**
  319. * Range marked by the marker.
  320. *
  321. * @protected
  322. * @member {module:engine/model/liverange~LiveRange}
  323. */
  324. this._liveRange = this._attachLiveRange( liveRange );
  325. /**
  326. * Flag indicates if the marker is managed using operations or not.
  327. *
  328. * @private
  329. * @member {Boolean}
  330. */
  331. this._managedUsingOperations = managedUsingOperations;
  332. /**
  333. * Specifies whether the marker affects the data produced by the data pipeline
  334. * (is persisted in the editor's data).
  335. *
  336. * @private
  337. * @member {Boolean}
  338. */
  339. this._affectsData = affectsData;
  340. }
  341. /**
  342. * A value indicating if the marker is managed using operations.
  343. * See {@link ~Marker marker class description} to learn more about marker types.
  344. * See {@link module:engine/model/writer~Writer#addMarker}.
  345. *
  346. * @returns {Boolean}
  347. */
  348. get managedUsingOperations() {
  349. if ( !this._liveRange ) {
  350. throw new CKEditorError( 'marker-destroyed: Cannot use a destroyed marker instance.', this );
  351. }
  352. return this._managedUsingOperations;
  353. }
  354. /**
  355. * A value indicating if the marker changes the data.
  356. *
  357. * @returns {Boolean}
  358. */
  359. get affectsData() {
  360. if ( !this._liveRange ) {
  361. throw new CKEditorError( 'marker-destroyed: Cannot use a destroyed marker instance.', this );
  362. }
  363. return this._affectsData;
  364. }
  365. /**
  366. * Returns current marker start position.
  367. *
  368. * @returns {module:engine/model/position~Position}
  369. */
  370. getStart() {
  371. if ( !this._liveRange ) {
  372. throw new CKEditorError( 'marker-destroyed: Cannot use a destroyed marker instance.', this );
  373. }
  374. return this._liveRange.start.clone();
  375. }
  376. /**
  377. * Returns current marker end position.
  378. *
  379. * @returns {module:engine/model/position~Position}
  380. */
  381. getEnd() {
  382. if ( !this._liveRange ) {
  383. throw new CKEditorError( 'marker-destroyed: Cannot use a destroyed marker instance.', this );
  384. }
  385. return this._liveRange.end.clone();
  386. }
  387. /**
  388. * Returns a range that represents the current state of the marker.
  389. *
  390. * Keep in mind that returned value is a {@link module:engine/model/range~Range Range}, not a
  391. * {@link module:engine/model/liverange~LiveRange LiveRange}. This means that it is up-to-date and relevant only
  392. * until next model document change. Do not store values returned by this method. Instead, store {@link ~Marker#name}
  393. * and get `Marker` instance from {@link module:engine/model/markercollection~MarkerCollection MarkerCollection} every
  394. * time there is a need to read marker properties. This will guarantee that the marker has not been removed and
  395. * that it's data is up-to-date.
  396. *
  397. * @returns {module:engine/model/range~Range}
  398. */
  399. getRange() {
  400. if ( !this._liveRange ) {
  401. throw new CKEditorError( 'marker-destroyed: Cannot use a destroyed marker instance.', this );
  402. }
  403. return this._liveRange.toRange();
  404. }
  405. /**
  406. * Checks whether this object is of the given.
  407. *
  408. * marker.is( 'marker' ); // -> true
  409. * marker.is( 'model:marker' ); // -> true
  410. *
  411. * marker.is( 'view:element' ); // -> false
  412. * marker.is( 'documentSelection' ); // -> false
  413. *
  414. * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
  415. *
  416. * @param {String} type
  417. * @returns {Boolean}
  418. */
  419. is( type ) {
  420. return type === 'marker' || type === 'model:marker';
  421. }
  422. /**
  423. * Binds new live range to the marker and detach the old one if is attached.
  424. *
  425. * @protected
  426. * @param {module:engine/model/liverange~LiveRange} liveRange Live range to attach
  427. * @returns {module:engine/model/liverange~LiveRange} Attached live range.
  428. */
  429. _attachLiveRange( liveRange ) {
  430. if ( this._liveRange ) {
  431. this._detachLiveRange();
  432. }
  433. // Delegating does not work with namespaces. Alternatively, we could delegate all events (using `*`).
  434. liveRange.delegate( 'change:range' ).to( this );
  435. liveRange.delegate( 'change:content' ).to( this );
  436. this._liveRange = liveRange;
  437. return liveRange;
  438. }
  439. /**
  440. * Unbinds and destroys currently attached live range.
  441. *
  442. * @protected
  443. */
  444. _detachLiveRange() {
  445. this._liveRange.stopDelegating( 'change:range', this );
  446. this._liveRange.stopDelegating( 'change:content', this );
  447. this._liveRange.detach();
  448. this._liveRange = null;
  449. }
  450. /**
  451. * Fired whenever {@link ~Marker#_liveRange marker range} is changed due to changes on {@link module:engine/model/document~Document}.
  452. * This is a delegated {@link module:engine/model/liverange~LiveRange#event:change:range LiveRange change:range event}.
  453. *
  454. * When marker is removed from {@link module:engine/model/markercollection~MarkerCollection MarkerCollection},
  455. * all event listeners listening to it should be removed. It is best to do it on
  456. * {@link module:engine/model/markercollection~MarkerCollection#event:update MarkerCollection update event}.
  457. *
  458. * @see module:engine/model/liverange~LiveRange#event:change:range
  459. * @event change:range
  460. * @param {module:engine/model/range~Range} oldRange
  461. * @param {Object} data
  462. */
  463. /**
  464. * Fired whenever change on {@link module:engine/model/document~Document} is done inside {@link ~Marker#_liveRange marker range}.
  465. * This is a delegated {@link module:engine/model/liverange~LiveRange#event:change:content LiveRange change:content event}.
  466. *
  467. * When marker is removed from {@link module:engine/model/markercollection~MarkerCollection MarkerCollection},
  468. * all event listeners listening to it should be removed. It is best to do it on
  469. * {@link module:engine/model/markercollection~MarkerCollection#event:update MarkerCollection update event}.
  470. *
  471. * @see module:engine/model/liverange~LiveRange#event:change:content
  472. * @event change:content
  473. * @param {module:engine/model/range~Range} oldRange
  474. * @param {Object} data
  475. */
  476. }
  477. mix( Marker, EmitterMixin );
  478. /**
  479. * Cannot use a {@link module:engine/model/markercollection~MarkerCollection#destroy destroyed marker} instance.
  480. *
  481. * @error marker-destroyed
  482. */