emittermixin.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/emittermixin
  7. */
  8. import EventInfo from './eventinfo';
  9. import uid from './uid';
  10. import priorities from './priorities';
  11. const _listeningTo = Symbol( 'listeningTo' );
  12. const _emitterId = Symbol( 'emitterId' );
  13. /**
  14. * Mixin that injects the {@link ~Emitter events API} into its host.
  15. *
  16. * @mixin EmitterMixin
  17. * @implements module:utils/emittermixin~Emitter
  18. */
  19. const EmitterMixin = {
  20. /**
  21. * @inheritDoc
  22. */
  23. on( event, callback, options = {} ) {
  24. this.listenTo( this, event, callback, options );
  25. },
  26. /**
  27. * @inheritDoc
  28. */
  29. once( event, callback, options ) {
  30. let wasFired = false;
  31. const onceCallback = function( event, ...args ) {
  32. // Ensure the callback is called only once even if the callback itself leads to re-firing the event
  33. // (which would call the callback again).
  34. if ( !wasFired ) {
  35. wasFired = true;
  36. // Go off() at the first call.
  37. event.off();
  38. // Go with the original callback.
  39. callback.call( this, event, ...args );
  40. }
  41. };
  42. // Make a similar on() call, simply replacing the callback.
  43. this.listenTo( this, event, onceCallback, options );
  44. },
  45. /**
  46. * @inheritDoc
  47. */
  48. off( event, callback ) {
  49. this.stopListening( this, event, callback );
  50. },
  51. /**
  52. * @inheritDoc
  53. */
  54. listenTo( emitter, event, callback, options = {} ) {
  55. let emitterInfo, eventCallbacks;
  56. // _listeningTo contains a list of emitters that this object is listening to.
  57. // This list has the following format:
  58. //
  59. // _listeningTo: {
  60. // emitterId: {
  61. // emitter: emitter,
  62. // callbacks: {
  63. // event1: [ callback1, callback2, ... ]
  64. // ....
  65. // }
  66. // },
  67. // ...
  68. // }
  69. if ( !this[ _listeningTo ] ) {
  70. this[ _listeningTo ] = {};
  71. }
  72. const emitters = this[ _listeningTo ];
  73. if ( !_getEmitterId( emitter ) ) {
  74. _setEmitterId( emitter );
  75. }
  76. const emitterId = _getEmitterId( emitter );
  77. if ( !( emitterInfo = emitters[ emitterId ] ) ) {
  78. emitterInfo = emitters[ emitterId ] = {
  79. emitter,
  80. callbacks: {}
  81. };
  82. }
  83. if ( !( eventCallbacks = emitterInfo.callbacks[ event ] ) ) {
  84. eventCallbacks = emitterInfo.callbacks[ event ] = [];
  85. }
  86. eventCallbacks.push( callback );
  87. // Finally register the callback to the event.
  88. createEventNamespace( emitter, event );
  89. const lists = getCallbacksListsForNamespace( emitter, event );
  90. const priority = priorities.get( options.priority );
  91. const callbackDefinition = {
  92. callback,
  93. priority
  94. };
  95. // Add the callback to all callbacks list.
  96. for ( const callbacks of lists ) {
  97. // Add the callback to the list in the right priority position.
  98. let added = false;
  99. for ( let i = 0; i < callbacks.length; i++ ) {
  100. if ( callbacks[ i ].priority < priority ) {
  101. callbacks.splice( i, 0, callbackDefinition );
  102. added = true;
  103. break;
  104. }
  105. }
  106. // Add at the end, if right place was not found.
  107. if ( !added ) {
  108. callbacks.push( callbackDefinition );
  109. }
  110. }
  111. },
  112. /**
  113. * @inheritDoc
  114. */
  115. stopListening( emitter, event, callback ) {
  116. const emitters = this[ _listeningTo ];
  117. let emitterId = emitter && _getEmitterId( emitter );
  118. const emitterInfo = emitters && emitterId && emitters[ emitterId ];
  119. const eventCallbacks = emitterInfo && event && emitterInfo.callbacks[ event ];
  120. // Stop if nothing has been listened.
  121. if ( !emitters || ( emitter && !emitterInfo ) || ( event && !eventCallbacks ) ) {
  122. return;
  123. }
  124. // All params provided. off() that single callback.
  125. if ( callback ) {
  126. removeCallback( emitter, event, callback );
  127. }
  128. // Only `emitter` and `event` provided. off() all callbacks for that event.
  129. else if ( eventCallbacks ) {
  130. while ( ( callback = eventCallbacks.pop() ) ) {
  131. removeCallback( emitter, event, callback );
  132. }
  133. delete emitterInfo.callbacks[ event ];
  134. }
  135. // Only `emitter` provided. off() all events for that emitter.
  136. else if ( emitterInfo ) {
  137. for ( event in emitterInfo.callbacks ) {
  138. this.stopListening( emitter, event );
  139. }
  140. delete emitters[ emitterId ];
  141. }
  142. // No params provided. off() all emitters.
  143. else {
  144. for ( emitterId in emitters ) {
  145. this.stopListening( emitters[ emitterId ].emitter );
  146. }
  147. delete this[ _listeningTo ];
  148. }
  149. },
  150. /**
  151. * @inheritDoc
  152. */
  153. fire( eventOrInfo, ...args ) {
  154. const eventInfo = eventOrInfo instanceof EventInfo ? eventOrInfo : new EventInfo( this, eventOrInfo );
  155. const event = eventInfo.name;
  156. let callbacks = getCallbacksForEvent( this, event );
  157. // Record that the event passed this emitter on its path.
  158. eventInfo.path.push( this );
  159. // Handle event listener callbacks first.
  160. if ( callbacks ) {
  161. // Arguments passed to each callback.
  162. const callbackArgs = [ eventInfo, ...args ];
  163. // Copying callbacks array is the easiest and most secure way of preventing infinite loops, when event callbacks
  164. // are added while processing other callbacks. Previous solution involved adding counters (unique ids) but
  165. // failed if callbacks were added to the queue before currently processed callback.
  166. // If this proves to be too inefficient, another method is to change `.on()` so callbacks are stored if same
  167. // event is currently processed. Then, `.fire()` at the end, would have to add all stored events.
  168. callbacks = Array.from( callbacks );
  169. for ( let i = 0; i < callbacks.length; i++ ) {
  170. callbacks[ i ].callback.apply( this, callbackArgs );
  171. // Remove the callback from future requests if off() has been called.
  172. if ( eventInfo.off.called ) {
  173. // Remove the called mark for the next calls.
  174. delete eventInfo.off.called;
  175. removeCallback( this, event, callbacks[ i ].callback );
  176. }
  177. // Do not execute next callbacks if stop() was called.
  178. if ( eventInfo.stop.called ) {
  179. break;
  180. }
  181. }
  182. }
  183. // Delegate event to other emitters if needed.
  184. if ( this._delegations ) {
  185. const destinations = this._delegations.get( event );
  186. const passAllDestinations = this._delegations.get( '*' );
  187. if ( destinations ) {
  188. fireDelegatedEvents( destinations, eventInfo, args );
  189. }
  190. if ( passAllDestinations ) {
  191. fireDelegatedEvents( passAllDestinations, eventInfo, args );
  192. }
  193. }
  194. return eventInfo.return;
  195. },
  196. /**
  197. * @inheritDoc
  198. */
  199. delegate( ...events ) {
  200. return {
  201. to: ( emitter, nameOrFunction ) => {
  202. if ( !this._delegations ) {
  203. this._delegations = new Map();
  204. }
  205. // Originally there was a for..of loop which unfortunately caused an error in Babel that didn't allow
  206. // build an application. See: https://github.com/ckeditor/ckeditor5-react/issues/40.
  207. events.forEach( eventName => {
  208. const destinations = this._delegations.get( eventName );
  209. if ( !destinations ) {
  210. this._delegations.set( eventName, new Map( [ [ emitter, nameOrFunction ] ] ) );
  211. } else {
  212. destinations.set( emitter, nameOrFunction );
  213. }
  214. } );
  215. }
  216. };
  217. },
  218. /**
  219. * @inheritDoc
  220. */
  221. stopDelegating( event, emitter ) {
  222. if ( !this._delegations ) {
  223. return;
  224. }
  225. if ( !event ) {
  226. this._delegations.clear();
  227. } else if ( !emitter ) {
  228. this._delegations.delete( event );
  229. } else {
  230. const destinations = this._delegations.get( event );
  231. if ( destinations ) {
  232. destinations.delete( emitter );
  233. }
  234. }
  235. }
  236. };
  237. export default EmitterMixin;
  238. /**
  239. * Emitter/listener interface.
  240. *
  241. * Can be easily implemented by a class by mixing the {@link module:utils/emittermixin~EmitterMixin} mixin.
  242. *
  243. * @interface Emitter
  244. */
  245. /**
  246. * Registers a callback function to be executed when an event is fired.
  247. *
  248. * Shorthand for {@link #listenTo `this.listenTo( this, event, callback, options )`} (it makes the emitter
  249. * listen on itself).
  250. *
  251. * @method #on
  252. * @param {String} event The name of the event.
  253. * @param {Function} callback The function to be called on event.
  254. * @param {Object} [options={}] Additional options.
  255. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  256. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  257. * order they were added.
  258. */
  259. /**
  260. * Registers a callback function to be executed on the next time the event is fired only. This is similar to
  261. * calling {@link #on} followed by {@link #off} in the callback.
  262. *
  263. * @method #once
  264. * @param {String} event The name of the event.
  265. * @param {Function} callback The function to be called on event.
  266. * @param {Object} [options={}] Additional options.
  267. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  268. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  269. * order they were added.
  270. */
  271. /**
  272. * Stops executing the callback on the given event.
  273. * Shorthand for {@link #stopListening `this.stopListening( this, event, callback )`}.
  274. *
  275. * @method #off
  276. * @param {String} event The name of the event.
  277. * @param {Function} callback The function to stop being called.
  278. */
  279. /**
  280. * Registers a callback function to be executed when an event is fired in a specific (emitter) object.
  281. *
  282. * Events can be grouped in namespaces using `:`.
  283. * When namespaced event is fired, it additionally fires all callbacks for that namespace.
  284. *
  285. * // myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
  286. * myEmitter.on( 'myGroup', genericCallback );
  287. * myEmitter.on( 'myGroup:myEvent', specificCallback );
  288. *
  289. * // genericCallback is fired.
  290. * myEmitter.fire( 'myGroup' );
  291. * // both genericCallback and specificCallback are fired.
  292. * myEmitter.fire( 'myGroup:myEvent' );
  293. * // genericCallback is fired even though there are no callbacks for "foo".
  294. * myEmitter.fire( 'myGroup:foo' );
  295. *
  296. * An event callback can {@link module:utils/eventinfo~EventInfo#stop stop the event} and
  297. * set the {@link module:utils/eventinfo~EventInfo#return return value} of the {@link #fire} method.
  298. *
  299. * @method #listenTo
  300. * @param {module:utils/emittermixin~Emitter} emitter The object that fires the event.
  301. * @param {String} event The name of the event.
  302. * @param {Function} callback The function to be called on event.
  303. * @param {Object} [options={}] Additional options.
  304. * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
  305. * the priority value the sooner the callback will be fired. Events having the same priority are called in the
  306. * order they were added.
  307. */
  308. /**
  309. * Stops listening for events. It can be used at different levels:
  310. *
  311. * * To stop listening to a specific callback.
  312. * * To stop listening to a specific event.
  313. * * To stop listening to all events fired by a specific object.
  314. * * To stop listening to all events fired by all objects.
  315. *
  316. * @method #stopListening
  317. * @param {module:utils/emittermixin~Emitter} [emitter] The object to stop listening to. If omitted, stops it for all objects.
  318. * @param {String} [event] (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it
  319. * for all events from `emitter`.
  320. * @param {Function} [callback] (Requires the `event`) The function to be removed from the call list for the given
  321. * `event`.
  322. */
  323. /**
  324. * Fires an event, executing all callbacks registered for it.
  325. *
  326. * The first parameter passed to callbacks is an {@link module:utils/eventinfo~EventInfo} object,
  327. * followed by the optional `args` provided in the `fire()` method call.
  328. *
  329. * @method #fire
  330. * @param {String|module:utils/eventinfo~EventInfo} eventOrInfo The name of the event or `EventInfo` object if event is delegated.
  331. * @param {...*} [args] Additional arguments to be passed to the callbacks.
  332. * @returns {*} By default the method returns `undefined`. However, the return value can be changed by listeners
  333. * through modification of the {@link module:utils/eventinfo~EventInfo#return `evt.return`}'s property (the event info
  334. * is the first param of every callback).
  335. */
  336. /**
  337. * Delegates selected events to another {@link module:utils/emittermixin~Emitter}. For instance:
  338. *
  339. * emitterA.delegate( 'eventX' ).to( emitterB );
  340. * emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
  341. *
  342. * then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:
  343. *
  344. * emitterA.fire( 'eventX', data );
  345. *
  346. * and `eventY` is delegated (fired by) `emitterC` along with `data`:
  347. *
  348. * emitterA.fire( 'eventY', data );
  349. *
  350. * @method #delegate
  351. * @param {...String} events Event names that will be delegated to another emitter.
  352. * @returns {module:utils/emittermixin~EmitterMixinDelegateChain}
  353. */
  354. /**
  355. * Stops delegating events. It can be used at different levels:
  356. *
  357. * * To stop delegating all events.
  358. * * To stop delegating a specific event to all emitters.
  359. * * To stop delegating a specific event to a specific emitter.
  360. *
  361. * @method #stopDelegating
  362. * @param {String} [event] The name of the event to stop delegating. If omitted, stops it all delegations.
  363. * @param {module:utils/emittermixin~Emitter} [emitter] (requires `event`) The object to stop delegating a particular event to.
  364. * If omitted, stops delegation of `event` to all emitters.
  365. */
  366. /**
  367. * Checks if `listeningEmitter` listens to an emitter with given `listenedToEmitterId` and if so, returns that emitter.
  368. * If not, returns `null`.
  369. *
  370. * @protected
  371. * @param {module:utils/emittermixin~EmitterMixin} listeningEmitter Emitter that listens.
  372. * @param {String} listenedToEmitterId Unique emitter id of emitter listened to.
  373. * @returns {module:utils/emittermixin~EmitterMixin|null}
  374. */
  375. export function _getEmitterListenedTo( listeningEmitter, listenedToEmitterId ) {
  376. if ( listeningEmitter[ _listeningTo ] && listeningEmitter[ _listeningTo ][ listenedToEmitterId ] ) {
  377. return listeningEmitter[ _listeningTo ][ listenedToEmitterId ].emitter;
  378. }
  379. return null;
  380. }
  381. /**
  382. * Sets emitter's unique id.
  383. *
  384. * **Note:** `_emitterId` can be set only once.
  385. *
  386. * @protected
  387. * @param {module:utils/emittermixin~EmitterMixin} emitter Emitter for which id will be set.
  388. * @param {String} [id] Unique id to set. If not passed, random unique id will be set.
  389. */
  390. export function _setEmitterId( emitter, id ) {
  391. if ( !emitter[ _emitterId ] ) {
  392. emitter[ _emitterId ] = id || uid();
  393. }
  394. }
  395. /**
  396. * Returns emitter's unique id.
  397. *
  398. * @protected
  399. * @param {module:utils/emittermixin~EmitterMixin} emitter Emitter which id will be returned.
  400. */
  401. export function _getEmitterId( emitter ) {
  402. return emitter[ _emitterId ];
  403. }
  404. // Gets the internal `_events` property of the given object.
  405. // `_events` property store all lists with callbacks for registered event names.
  406. // If there were no events registered on the object, empty `_events` object is created.
  407. function getEvents( source ) {
  408. if ( !source._events ) {
  409. Object.defineProperty( source, '_events', {
  410. value: {}
  411. } );
  412. }
  413. return source._events;
  414. }
  415. // Creates event node for generic-specific events relation architecture.
  416. function makeEventNode() {
  417. return {
  418. callbacks: [],
  419. childEvents: []
  420. };
  421. }
  422. // Creates an architecture for generic-specific events relation.
  423. // If needed, creates all events for given eventName, i.e. if the first registered event
  424. // is foo:bar:abc, it will create foo:bar:abc, foo:bar and foo event and tie them together.
  425. // It also copies callbacks from more generic events to more specific events when
  426. // specific events are created.
  427. function createEventNamespace( source, eventName ) {
  428. const events = getEvents( source );
  429. // First, check if the event we want to add to the structure already exists.
  430. if ( events[ eventName ] ) {
  431. // If it exists, we don't have to do anything.
  432. return;
  433. }
  434. // In other case, we have to create the structure for the event.
  435. // Note, that we might need to create intermediate events too.
  436. // I.e. if foo:bar:abc is being registered and we only have foo in the structure,
  437. // we need to also register foo:bar.
  438. // Currently processed event name.
  439. let name = eventName;
  440. // Name of the event that is a child event for currently processed event.
  441. let childEventName = null;
  442. // Array containing all newly created specific events.
  443. const newEventNodes = [];
  444. // While loop can't check for ':' index because we have to handle generic events too.
  445. // In each loop, we truncate event name, going from the most specific name to the generic one.
  446. // I.e. foo:bar:abc -> foo:bar -> foo.
  447. while ( name !== '' ) {
  448. if ( events[ name ] ) {
  449. // If the currently processed event name is already registered, we can be sure
  450. // that it already has all the structure created, so we can break the loop here
  451. // as no more events need to be registered.
  452. break;
  453. }
  454. // If this event is not yet registered, create a new object for it.
  455. events[ name ] = makeEventNode();
  456. // Add it to the array with newly created events.
  457. newEventNodes.push( events[ name ] );
  458. // Add previously processed event name as a child of this event.
  459. if ( childEventName ) {
  460. events[ name ].childEvents.push( childEventName );
  461. }
  462. childEventName = name;
  463. // If `.lastIndexOf()` returns -1, `.substr()` will return '' which will break the loop.
  464. name = name.substr( 0, name.lastIndexOf( ':' ) );
  465. }
  466. if ( name !== '' ) {
  467. // If name is not empty, we found an already registered event that was a parent of the
  468. // event we wanted to register.
  469. // Copy that event's callbacks to newly registered events.
  470. for ( const node of newEventNodes ) {
  471. node.callbacks = events[ name ].callbacks.slice();
  472. }
  473. // Add last newly created event to the already registered event.
  474. events[ name ].childEvents.push( childEventName );
  475. }
  476. }
  477. // Gets an array containing callbacks list for a given event and it's more specific events.
  478. // I.e. if given event is foo:bar and there is also foo:bar:abc event registered, this will
  479. // return callback list of foo:bar and foo:bar:abc (but not foo).
  480. function getCallbacksListsForNamespace( source, eventName ) {
  481. const eventNode = getEvents( source )[ eventName ];
  482. if ( !eventNode ) {
  483. return [];
  484. }
  485. let callbacksLists = [ eventNode.callbacks ];
  486. for ( let i = 0; i < eventNode.childEvents.length; i++ ) {
  487. const childCallbacksLists = getCallbacksListsForNamespace( source, eventNode.childEvents[ i ] );
  488. callbacksLists = callbacksLists.concat( childCallbacksLists );
  489. }
  490. return callbacksLists;
  491. }
  492. // Get the list of callbacks for a given event, but only if there any callbacks have been registered.
  493. // If there are no callbacks registered for given event, it checks if this is a specific event and looks
  494. // for callbacks for it's more generic version.
  495. function getCallbacksForEvent( source, eventName ) {
  496. let event;
  497. if ( !source._events || !( event = source._events[ eventName ] ) || !event.callbacks.length ) {
  498. // There are no callbacks registered for specified eventName.
  499. // But this could be a specific-type event that is in a namespace.
  500. if ( eventName.indexOf( ':' ) > -1 ) {
  501. // If the eventName is specific, try to find callback lists for more generic event.
  502. return getCallbacksForEvent( source, eventName.substr( 0, eventName.lastIndexOf( ':' ) ) );
  503. } else {
  504. // If this is a top-level generic event, return null;
  505. return null;
  506. }
  507. }
  508. return event.callbacks;
  509. }
  510. // Fires delegated events for given map of destinations.
  511. //
  512. // @private
  513. // * @param {Map.<utils.Emitter>} destinations A map containing `[ {@link utils.Emitter}, "event name" ]` pair destinations.
  514. // * @param {utils.EventInfo} eventInfo The original event info object.
  515. // * @param {Array.<*>} fireArgs Arguments the original event was fired with.
  516. function fireDelegatedEvents( destinations, eventInfo, fireArgs ) {
  517. for ( let [ emitter, name ] of destinations ) {
  518. if ( !name ) {
  519. name = eventInfo.name;
  520. } else if ( typeof name == 'function' ) {
  521. name = name( eventInfo.name );
  522. }
  523. const delegatedInfo = new EventInfo( eventInfo.source, name );
  524. delegatedInfo.path = [ ...eventInfo.path ];
  525. emitter.fire( delegatedInfo, ...fireArgs );
  526. }
  527. }
  528. // Removes callback from emitter for given event.
  529. //
  530. // @param {module:utils/emittermixin~Emitter} emitter
  531. // @param {String} event
  532. // @param {Function} callback
  533. function removeCallback( emitter, event, callback ) {
  534. const lists = getCallbacksListsForNamespace( emitter, event );
  535. for ( const callbacks of lists ) {
  536. for ( let i = 0; i < callbacks.length; i++ ) {
  537. if ( callbacks[ i ].callback == callback ) {
  538. // Remove the callback from the list (fixing the next index).
  539. callbacks.splice( i, 1 );
  540. i--;
  541. }
  542. }
  543. }
  544. }
  545. /**
  546. * The return value of {@link ~EmitterMixin#delegate}.
  547. *
  548. * @interface module:utils/emittermixin~EmitterMixinDelegateChain
  549. */
  550. /**
  551. * Selects destination for {@link module:utils/emittermixin~EmitterMixin#delegate} events.
  552. *
  553. * @method #to
  554. * @param {module:utils/emittermixin~Emitter} emitter An `EmitterMixin` instance which is the destination for delegated events.
  555. * @param {String|Function} [nameOrFunction] A custom event name or function which converts the original name string.
  556. */