markercollection.js 19 KB

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