8
0

markercollection.js 19 KB

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