@ckeditor/ckeditor5-utils 34.2.0 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +324 -0
  2. package/LICENSE.md +1 -1
  3. package/package.json +19 -8
  4. package/src/areconnectedthroughproperties.js +54 -71
  5. package/src/ckeditorerror.js +92 -114
  6. package/src/collection.js +594 -762
  7. package/src/comparearrays.js +22 -28
  8. package/src/config.js +193 -223
  9. package/src/count.js +8 -12
  10. package/src/diff.js +85 -110
  11. package/src/difftochanges.js +47 -57
  12. package/src/dom/createelement.js +17 -25
  13. package/src/dom/emittermixin.js +202 -263
  14. package/src/dom/getancestors.js +9 -13
  15. package/src/dom/getborderwidths.js +10 -13
  16. package/src/dom/getcommonancestor.js +9 -15
  17. package/src/dom/getdatafromelement.js +5 -9
  18. package/src/dom/getpositionedancestor.js +9 -14
  19. package/src/dom/global.js +15 -4
  20. package/src/dom/indexof.js +7 -11
  21. package/src/dom/insertat.js +2 -4
  22. package/src/dom/iscomment.js +2 -5
  23. package/src/dom/isnode.js +10 -12
  24. package/src/dom/isrange.js +2 -4
  25. package/src/dom/istext.js +2 -4
  26. package/src/dom/isvisible.js +2 -4
  27. package/src/dom/iswindow.js +11 -16
  28. package/src/dom/position.js +220 -410
  29. package/src/dom/rect.js +335 -414
  30. package/src/dom/remove.js +5 -8
  31. package/src/dom/resizeobserver.js +109 -342
  32. package/src/dom/scroll.js +151 -183
  33. package/src/dom/setdatainelement.js +5 -9
  34. package/src/dom/tounit.js +10 -12
  35. package/src/elementreplacer.js +30 -44
  36. package/src/emittermixin.js +368 -634
  37. package/src/env.js +109 -116
  38. package/src/eventinfo.js +12 -65
  39. package/src/fastdiff.js +96 -128
  40. package/src/first.js +8 -12
  41. package/src/focustracker.js +77 -133
  42. package/src/index.js +0 -9
  43. package/src/inserttopriorityarray.js +9 -30
  44. package/src/isiterable.js +2 -4
  45. package/src/keyboard.js +117 -196
  46. package/src/keystrokehandler.js +72 -88
  47. package/src/language.js +9 -15
  48. package/src/locale.js +61 -158
  49. package/src/mapsequal.js +12 -17
  50. package/src/mix.js +17 -16
  51. package/src/nth.js +8 -11
  52. package/src/objecttomap.js +7 -11
  53. package/src/observablemixin.js +474 -778
  54. package/src/priorities.js +20 -32
  55. package/src/spy.js +3 -6
  56. package/src/toarray.js +2 -13
  57. package/src/tomap.js +8 -10
  58. package/src/translation-service.js +57 -93
  59. package/src/uid.js +34 -38
  60. package/src/unicode.js +28 -43
  61. package/src/version.js +134 -143
@@ -2,23 +2,20 @@
2
2
  * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module utils/emittermixin
8
7
  */
9
-
8
+ /* eslint-disable new-cap */
10
9
  import EventInfo from './eventinfo';
11
10
  import uid from './uid';
12
11
  import priorities from './priorities';
13
12
  import insertToPriorityArray from './inserttopriorityarray';
14
-
15
13
  // To check if component is loaded more than once.
16
14
  import './version';
17
15
  import CKEditorError from './ckeditorerror';
18
-
19
- const _listeningTo = Symbol( 'listeningTo' );
20
- const _emitterId = Symbol( 'emitterId' );
21
-
16
+ const _listeningTo = Symbol('listeningTo');
17
+ const _emitterId = Symbol('emitterId');
18
+ const _delegations = Symbol('delegations');
22
19
  /**
23
20
  * Mixin that injects the {@link ~Emitter events API} into its host.
24
21
  *
@@ -30,635 +27,388 @@ const _emitterId = Symbol( 'emitterId' );
30
27
  * @mixin EmitterMixin
31
28
  * @implements module:utils/emittermixin~Emitter
32
29
  */
33
- const EmitterMixin = {
34
- /**
35
- * @inheritDoc
36
- */
37
- on( event, callback, options = {} ) {
38
- this.listenTo( this, event, callback, options );
39
- },
40
-
41
- /**
42
- * @inheritDoc
43
- */
44
- once( event, callback, options ) {
45
- let wasFired = false;
46
-
47
- const onceCallback = function( event, ...args ) {
48
- // Ensure the callback is called only once even if the callback itself leads to re-firing the event
49
- // (which would call the callback again).
50
- if ( !wasFired ) {
51
- wasFired = true;
52
-
53
- // Go off() at the first call.
54
- event.off();
55
-
56
- // Go with the original callback.
57
- callback.call( this, event, ...args );
58
- }
59
- };
60
-
61
- // Make a similar on() call, simply replacing the callback.
62
- this.listenTo( this, event, onceCallback, options );
63
- },
64
-
65
- /**
66
- * @inheritDoc
67
- */
68
- off( event, callback ) {
69
- this.stopListening( this, event, callback );
70
- },
71
-
72
- /**
73
- * @inheritDoc
74
- */
75
- listenTo( emitter, event, callback, options = {} ) {
76
- let emitterInfo, eventCallbacks;
77
-
78
- // _listeningTo contains a list of emitters that this object is listening to.
79
- // This list has the following format:
80
- //
81
- // _listeningTo: {
82
- // emitterId: {
83
- // emitter: emitter,
84
- // callbacks: {
85
- // event1: [ callback1, callback2, ... ]
86
- // ....
87
- // }
88
- // },
89
- // ...
90
- // }
91
-
92
- if ( !this[ _listeningTo ] ) {
93
- this[ _listeningTo ] = {};
94
- }
95
-
96
- const emitters = this[ _listeningTo ];
97
-
98
- if ( !_getEmitterId( emitter ) ) {
99
- _setEmitterId( emitter );
100
- }
101
-
102
- const emitterId = _getEmitterId( emitter );
103
-
104
- if ( !( emitterInfo = emitters[ emitterId ] ) ) {
105
- emitterInfo = emitters[ emitterId ] = {
106
- emitter,
107
- callbacks: {}
108
- };
109
- }
110
-
111
- if ( !( eventCallbacks = emitterInfo.callbacks[ event ] ) ) {
112
- eventCallbacks = emitterInfo.callbacks[ event ] = [];
113
- }
114
-
115
- eventCallbacks.push( callback );
116
-
117
- // Finally register the callback to the event.
118
- addEventListener( this, emitter, event, callback, options );
119
- },
120
-
121
- /**
122
- * @inheritDoc
123
- */
124
- stopListening( emitter, event, callback ) {
125
- const emitters = this[ _listeningTo ];
126
- let emitterId = emitter && _getEmitterId( emitter );
127
- const emitterInfo = emitters && emitterId && emitters[ emitterId ];
128
- const eventCallbacks = emitterInfo && event && emitterInfo.callbacks[ event ];
129
-
130
- // Stop if nothing has been listened.
131
- if ( !emitters || ( emitter && !emitterInfo ) || ( event && !eventCallbacks ) ) {
132
- return;
133
- }
134
-
135
- // All params provided. off() that single callback.
136
- if ( callback ) {
137
- removeEventListener( this, emitter, event, callback );
138
-
139
- // We must remove callbacks as well in order to prevent memory leaks.
140
- // See https://github.com/ckeditor/ckeditor5/pull/8480
141
- const index = eventCallbacks.indexOf( callback );
142
-
143
- if ( index !== -1 ) {
144
- if ( eventCallbacks.length === 1 ) {
145
- delete emitterInfo.callbacks[ event ];
146
- } else {
147
- removeEventListener( this, emitter, event, callback );
148
- }
149
- }
150
- }
151
- // Only `emitter` and `event` provided. off() all callbacks for that event.
152
- else if ( eventCallbacks ) {
153
- while ( ( callback = eventCallbacks.pop() ) ) {
154
- removeEventListener( this, emitter, event, callback );
155
- }
156
-
157
- delete emitterInfo.callbacks[ event ];
158
- }
159
- // Only `emitter` provided. off() all events for that emitter.
160
- else if ( emitterInfo ) {
161
- for ( event in emitterInfo.callbacks ) {
162
- this.stopListening( emitter, event );
163
- }
164
- delete emitters[ emitterId ];
165
- }
166
- // No params provided. off() all emitters.
167
- else {
168
- for ( emitterId in emitters ) {
169
- this.stopListening( emitters[ emitterId ].emitter );
170
- }
171
- delete this[ _listeningTo ];
172
- }
173
- },
174
-
175
- /**
176
- * @inheritDoc
177
- */
178
- fire( eventOrInfo, ...args ) {
179
- try {
180
- const eventInfo = eventOrInfo instanceof EventInfo ? eventOrInfo : new EventInfo( this, eventOrInfo );
181
- const event = eventInfo.name;
182
- let callbacks = getCallbacksForEvent( this, event );
183
-
184
- // Record that the event passed this emitter on its path.
185
- eventInfo.path.push( this );
186
-
187
- // Handle event listener callbacks first.
188
- if ( callbacks ) {
189
- // Arguments passed to each callback.
190
- const callbackArgs = [ eventInfo, ...args ];
191
-
192
- // Copying callbacks array is the easiest and most secure way of preventing infinite loops, when event callbacks
193
- // are added while processing other callbacks. Previous solution involved adding counters (unique ids) but
194
- // failed if callbacks were added to the queue before currently processed callback.
195
- // If this proves to be too inefficient, another method is to change `.on()` so callbacks are stored if same
196
- // event is currently processed. Then, `.fire()` at the end, would have to add all stored events.
197
- callbacks = Array.from( callbacks );
198
-
199
- for ( let i = 0; i < callbacks.length; i++ ) {
200
- callbacks[ i ].callback.apply( this, callbackArgs );
201
-
202
- // Remove the callback from future requests if off() has been called.
203
- if ( eventInfo.off.called ) {
204
- // Remove the called mark for the next calls.
205
- delete eventInfo.off.called;
206
-
207
- this._removeEventListener( event, callbacks[ i ].callback );
208
- }
209
-
210
- // Do not execute next callbacks if stop() was called.
211
- if ( eventInfo.stop.called ) {
212
- break;
213
- }
214
- }
215
- }
216
-
217
- // Delegate event to other emitters if needed.
218
- if ( this._delegations ) {
219
- const destinations = this._delegations.get( event );
220
- const passAllDestinations = this._delegations.get( '*' );
221
-
222
- if ( destinations ) {
223
- fireDelegatedEvents( destinations, eventInfo, args );
224
- }
225
-
226
- if ( passAllDestinations ) {
227
- fireDelegatedEvents( passAllDestinations, eventInfo, args );
228
- }
229
- }
230
-
231
- return eventInfo.return;
232
- } catch ( err ) {
233
- // @if CK_DEBUG // throw err;
234
- /* istanbul ignore next */
235
- CKEditorError.rethrowUnexpectedError( err, this );
236
- }
237
- },
238
-
239
- /**
240
- * @inheritDoc
241
- */
242
- delegate( ...events ) {
243
- return {
244
- to: ( emitter, nameOrFunction ) => {
245
- if ( !this._delegations ) {
246
- this._delegations = new Map();
247
- }
248
-
249
- // Originally there was a for..of loop which unfortunately caused an error in Babel that didn't allow
250
- // build an application. See: https://github.com/ckeditor/ckeditor5-react/issues/40.
251
- events.forEach( eventName => {
252
- const destinations = this._delegations.get( eventName );
253
-
254
- if ( !destinations ) {
255
- this._delegations.set( eventName, new Map( [ [ emitter, nameOrFunction ] ] ) );
256
- } else {
257
- destinations.set( emitter, nameOrFunction );
258
- }
259
- } );
260
- }
261
- };
262
- },
263
-
264
- /**
265
- * @inheritDoc
266
- */
267
- stopDelegating( event, emitter ) {
268
- if ( !this._delegations ) {
269
- return;
270
- }
271
-
272
- if ( !event ) {
273
- this._delegations.clear();
274
- } else if ( !emitter ) {
275
- this._delegations.delete( event );
276
- } else {
277
- const destinations = this._delegations.get( event );
278
-
279
- if ( destinations ) {
280
- destinations.delete( emitter );
281
- }
282
- }
283
- },
284
-
285
- /**
286
- * @inheritDoc
287
- */
288
- _addEventListener( event, callback, options ) {
289
- createEventNamespace( this, event );
290
-
291
- const lists = getCallbacksListsForNamespace( this, event );
292
- const priority = priorities.get( options.priority );
293
-
294
- const callbackDefinition = {
295
- callback,
296
- priority
297
- };
298
-
299
- // Add the callback to all callbacks list.
300
- for ( const callbacks of lists ) {
301
- // Add the callback to the list in the right priority position.
302
- insertToPriorityArray( callbacks, callbackDefinition );
303
- }
304
- },
305
-
306
- /**
307
- * @inheritDoc
308
- */
309
- _removeEventListener( event, callback ) {
310
- const lists = getCallbacksListsForNamespace( this, event );
311
-
312
- for ( const callbacks of lists ) {
313
- for ( let i = 0; i < callbacks.length; i++ ) {
314
- if ( callbacks[ i ].callback == callback ) {
315
- // Remove the callback from the list (fixing the next index).
316
- callbacks.splice( i, 1 );
317
- i--;
318
- }
319
- }
320
- }
321
- }
322
- };
323
-
324
- export default EmitterMixin;
325
-
326
- /**
327
- * Emitter/listener interface.
328
- *
329
- * Can be easily implemented by a class by mixing the {@link module:utils/emittermixin~EmitterMixin} mixin.
330
- *
331
- * Read more about the usage of this interface in the:
332
- * * {@glink framework/guides/architecture/core-editor-architecture#event-system-and-observables Event system and observables}
333
- * section of the {@glink framework/guides/architecture/core-editor-architecture Core editor architecture} guide.
334
- * * {@glink framework/guides/deep-dive/event-system Event system} deep dive guide.
335
- *
336
- * @interface Emitter
337
- */
338
-
339
- /**
340
- * Registers a callback function to be executed when an event is fired.
341
- *
342
- * Shorthand for {@link #listenTo `this.listenTo( this, event, callback, options )`} (it makes the emitter
343
- * listen on itself).
344
- *
345
- * @method #on
346
- * @param {String} event The name of the event.
347
- * @param {Function} callback The function to be called on event.
348
- * @param {Object} [options={}] Additional options.
349
- * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
350
- * the priority value the sooner the callback will be fired. Events having the same priority are called in the
351
- * order they were added.
352
- */
353
-
354
- /**
355
- * Registers a callback function to be executed on the next time the event is fired only. This is similar to
356
- * calling {@link #on} followed by {@link #off} in the callback.
357
- *
358
- * @method #once
359
- * @param {String} event The name of the event.
360
- * @param {Function} callback The function to be called on event.
361
- * @param {Object} [options={}] Additional options.
362
- * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
363
- * the priority value the sooner the callback will be fired. Events having the same priority are called in the
364
- * order they were added.
365
- */
366
-
367
- /**
368
- * Stops executing the callback on the given event.
369
- * Shorthand for {@link #stopListening `this.stopListening( this, event, callback )`}.
370
- *
371
- * @method #off
372
- * @param {String} event The name of the event.
373
- * @param {Function} callback The function to stop being called.
374
- */
375
-
376
- /**
377
- * Registers a callback function to be executed when an event is fired in a specific (emitter) object.
378
- *
379
- * Events can be grouped in namespaces using `:`.
380
- * When namespaced event is fired, it additionally fires all callbacks for that namespace.
381
- *
382
- * // myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
383
- * myEmitter.on( 'myGroup', genericCallback );
384
- * myEmitter.on( 'myGroup:myEvent', specificCallback );
385
- *
386
- * // genericCallback is fired.
387
- * myEmitter.fire( 'myGroup' );
388
- * // both genericCallback and specificCallback are fired.
389
- * myEmitter.fire( 'myGroup:myEvent' );
390
- * // genericCallback is fired even though there are no callbacks for "foo".
391
- * myEmitter.fire( 'myGroup:foo' );
392
- *
393
- * An event callback can {@link module:utils/eventinfo~EventInfo#stop stop the event} and
394
- * set the {@link module:utils/eventinfo~EventInfo#return return value} of the {@link #fire} method.
395
- *
396
- * @method #listenTo
397
- * @param {module:utils/emittermixin~Emitter} emitter The object that fires the event.
398
- * @param {String} event The name of the event.
399
- * @param {Function} callback The function to be called on event.
400
- * @param {Object} [options={}] Additional options.
401
- * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
402
- * the priority value the sooner the callback will be fired. Events having the same priority are called in the
403
- * order they were added.
404
- */
405
-
406
- /**
407
- * Stops listening for events. It can be used at different levels:
408
- *
409
- * * To stop listening to a specific callback.
410
- * * To stop listening to a specific event.
411
- * * To stop listening to all events fired by a specific object.
412
- * * To stop listening to all events fired by all objects.
413
- *
414
- * @method #stopListening
415
- * @param {module:utils/emittermixin~Emitter} [emitter] The object to stop listening to. If omitted, stops it for all objects.
416
- * @param {String} [event] (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it
417
- * for all events from `emitter`.
418
- * @param {Function} [callback] (Requires the `event`) The function to be removed from the call list for the given
419
- * `event`.
420
- */
421
-
422
- /**
423
- * Fires an event, executing all callbacks registered for it.
424
- *
425
- * The first parameter passed to callbacks is an {@link module:utils/eventinfo~EventInfo} object,
426
- * followed by the optional `args` provided in the `fire()` method call.
427
- *
428
- * @method #fire
429
- * @param {String|module:utils/eventinfo~EventInfo} eventOrInfo The name of the event or `EventInfo` object if event is delegated.
430
- * @param {...*} [args] Additional arguments to be passed to the callbacks.
431
- * @returns {*} By default the method returns `undefined`. However, the return value can be changed by listeners
432
- * through modification of the {@link module:utils/eventinfo~EventInfo#return `evt.return`}'s property (the event info
433
- * is the first param of every callback).
434
- */
435
-
436
- /**
437
- * Delegates selected events to another {@link module:utils/emittermixin~Emitter}. For instance:
438
- *
439
- * emitterA.delegate( 'eventX' ).to( emitterB );
440
- * emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
441
- *
442
- * then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:
443
- *
444
- * emitterA.fire( 'eventX', data );
445
- *
446
- * and `eventY` is delegated (fired by) `emitterC` along with `data`:
447
- *
448
- * emitterA.fire( 'eventY', data );
449
- *
450
- * @method #delegate
451
- * @param {...String} events Event names that will be delegated to another emitter.
452
- * @returns {module:utils/emittermixin~EmitterMixinDelegateChain}
453
- */
454
-
455
- /**
456
- * Stops delegating events. It can be used at different levels:
457
- *
458
- * * To stop delegating all events.
459
- * * To stop delegating a specific event to all emitters.
460
- * * To stop delegating a specific event to a specific emitter.
461
- *
462
- * @method #stopDelegating
463
- * @param {String} [event] The name of the event to stop delegating. If omitted, stops it all delegations.
464
- * @param {module:utils/emittermixin~Emitter} [emitter] (requires `event`) The object to stop delegating a particular event to.
465
- * If omitted, stops delegation of `event` to all emitters.
466
- */
467
-
468
- /**
469
- * Adds callback to emitter for given event.
470
- *
471
- * @protected
472
- * @method #_addEventListener
473
- * @param {String} event The name of the event.
474
- * @param {Function} callback The function to be called on event.
475
- * @param {Object} [options={}] Additional options.
476
- * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher
477
- * the priority value the sooner the callback will be fired. Events having the same priority are called in the
478
- * order they were added.
479
- */
480
-
481
- /**
482
- * Removes callback from emitter for given event.
483
- *
484
- * @protected
485
- * @method #_removeEventListener
486
- * @param {String} event The name of the event.
487
- * @param {Function} callback The function to stop being called.
488
- */
489
-
30
+ export default function EmitterMixin(base) {
31
+ class Mixin extends base {
32
+ on(event, callback, options) {
33
+ this.listenTo(this, event, callback, options);
34
+ }
35
+ once(event, callback, options) {
36
+ let wasFired = false;
37
+ const onceCallback = (event, ...args) => {
38
+ // Ensure the callback is called only once even if the callback itself leads to re-firing the event
39
+ // (which would call the callback again).
40
+ if (!wasFired) {
41
+ wasFired = true;
42
+ // Go off() at the first call.
43
+ event.off();
44
+ // Go with the original callback.
45
+ callback.call(this, event, ...args);
46
+ }
47
+ };
48
+ // Make a similar on() call, simply replacing the callback.
49
+ this.listenTo(this, event, onceCallback, options);
50
+ }
51
+ off(event, callback) {
52
+ this.stopListening(this, event, callback);
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
+ addEventListener(this, emitter, event, callback, options);
89
+ }
90
+ stopListening(emitter, event, callback) {
91
+ const emitters = this[_listeningTo];
92
+ let emitterId = emitter && _getEmitterId(emitter);
93
+ const emitterInfo = (emitters && emitterId) ? emitters[emitterId] : undefined;
94
+ const eventCallbacks = (emitterInfo && event) ? emitterInfo.callbacks[event] : undefined;
95
+ // Stop if nothing has been listened.
96
+ if (!emitters || (emitter && !emitterInfo) || (event && !eventCallbacks)) {
97
+ return;
98
+ }
99
+ // All params provided. off() that single callback.
100
+ if (callback) {
101
+ removeEventListener(this, emitter, event, callback);
102
+ // We must remove callbacks as well in order to prevent memory leaks.
103
+ // See https://github.com/ckeditor/ckeditor5/pull/8480
104
+ const index = eventCallbacks.indexOf(callback);
105
+ if (index !== -1) {
106
+ if (eventCallbacks.length === 1) {
107
+ delete emitterInfo.callbacks[event];
108
+ }
109
+ else {
110
+ removeEventListener(this, emitter, event, callback);
111
+ }
112
+ }
113
+ }
114
+ // Only `emitter` and `event` provided. off() all callbacks for that event.
115
+ else if (eventCallbacks) {
116
+ while ((callback = eventCallbacks.pop())) {
117
+ removeEventListener(this, emitter, event, callback);
118
+ }
119
+ delete emitterInfo.callbacks[event];
120
+ }
121
+ // Only `emitter` provided. off() all events for that emitter.
122
+ else if (emitterInfo) {
123
+ for (event in emitterInfo.callbacks) {
124
+ this.stopListening(emitter, event);
125
+ }
126
+ delete emitters[emitterId];
127
+ }
128
+ // No params provided. off() all emitters.
129
+ else {
130
+ for (emitterId in emitters) {
131
+ this.stopListening(emitters[emitterId].emitter);
132
+ }
133
+ delete this[_listeningTo];
134
+ }
135
+ }
136
+ fire(eventOrInfo, ...args) {
137
+ try {
138
+ const eventInfo = eventOrInfo instanceof EventInfo ? eventOrInfo : new EventInfo(this, eventOrInfo);
139
+ const event = eventInfo.name;
140
+ let callbacks = getCallbacksForEvent(this, event);
141
+ // Record that the event passed this emitter on its path.
142
+ eventInfo.path.push(this);
143
+ // Handle event listener callbacks first.
144
+ if (callbacks) {
145
+ // Arguments passed to each callback.
146
+ const callbackArgs = [eventInfo, ...args];
147
+ // Copying callbacks array is the easiest and most secure way of preventing infinite loops, when event callbacks
148
+ // are added while processing other callbacks. Previous solution involved adding counters (unique ids) but
149
+ // failed if callbacks were added to the queue before currently processed callback.
150
+ // If this proves to be too inefficient, another method is to change `.on()` so callbacks are stored if same
151
+ // event is currently processed. Then, `.fire()` at the end, would have to add all stored events.
152
+ callbacks = Array.from(callbacks);
153
+ for (let i = 0; i < callbacks.length; i++) {
154
+ callbacks[i].callback.apply(this, callbackArgs);
155
+ // Remove the callback from future requests if off() has been called.
156
+ if (eventInfo.off.called) {
157
+ // Remove the called mark for the next calls.
158
+ delete eventInfo.off.called;
159
+ this._removeEventListener(event, callbacks[i].callback);
160
+ }
161
+ // Do not execute next callbacks if stop() was called.
162
+ if (eventInfo.stop.called) {
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ // Delegate event to other emitters if needed.
168
+ const delegations = this[_delegations];
169
+ if (delegations) {
170
+ const destinations = delegations.get(event);
171
+ const passAllDestinations = delegations.get('*');
172
+ if (destinations) {
173
+ fireDelegatedEvents(destinations, eventInfo, args);
174
+ }
175
+ if (passAllDestinations) {
176
+ fireDelegatedEvents(passAllDestinations, eventInfo, args);
177
+ }
178
+ }
179
+ return eventInfo.return;
180
+ }
181
+ catch (err) {
182
+ // @if CK_DEBUG // throw err;
183
+ /* istanbul ignore next */
184
+ CKEditorError.rethrowUnexpectedError(err, this);
185
+ }
186
+ }
187
+ delegate(...events) {
188
+ return {
189
+ to: (emitter, nameOrFunction) => {
190
+ if (!this[_delegations]) {
191
+ this[_delegations] = new Map();
192
+ }
193
+ // Originally there was a for..of loop which unfortunately caused an error in Babel that didn't allow
194
+ // build an application. See: https://github.com/ckeditor/ckeditor5-react/issues/40.
195
+ events.forEach(eventName => {
196
+ const destinations = this[_delegations].get(eventName);
197
+ if (!destinations) {
198
+ this[_delegations].set(eventName, new Map([[emitter, nameOrFunction]]));
199
+ }
200
+ else {
201
+ destinations.set(emitter, nameOrFunction);
202
+ }
203
+ });
204
+ }
205
+ };
206
+ }
207
+ stopDelegating(event, emitter) {
208
+ if (!this[_delegations]) {
209
+ return;
210
+ }
211
+ if (!event) {
212
+ this[_delegations].clear();
213
+ }
214
+ else if (!emitter) {
215
+ this[_delegations].delete(event);
216
+ }
217
+ else {
218
+ const destinations = this[_delegations].get(event);
219
+ if (destinations) {
220
+ destinations.delete(emitter);
221
+ }
222
+ }
223
+ }
224
+ _addEventListener(event, callback, options) {
225
+ createEventNamespace(this, event);
226
+ const lists = getCallbacksListsForNamespace(this, event);
227
+ const priority = priorities.get(options.priority);
228
+ const callbackDefinition = {
229
+ callback,
230
+ priority
231
+ };
232
+ // Add the callback to all callbacks list.
233
+ for (const callbacks of lists) {
234
+ // Add the callback to the list in the right priority position.
235
+ insertToPriorityArray(callbacks, callbackDefinition);
236
+ }
237
+ }
238
+ _removeEventListener(event, callback) {
239
+ const lists = getCallbacksListsForNamespace(this, event);
240
+ for (const callbacks of lists) {
241
+ for (let i = 0; i < callbacks.length; i++) {
242
+ if (callbacks[i].callback == callback) {
243
+ // Remove the callback from the list (fixing the next index).
244
+ callbacks.splice(i, 1);
245
+ i--;
246
+ }
247
+ }
248
+ }
249
+ }
250
+ }
251
+ return Mixin;
252
+ }
253
+ export const Emitter = EmitterMixin(Object);
254
+ // Backward compatibility with `mix`
255
+ ([
256
+ 'on', 'once', 'off', 'listenTo',
257
+ 'stopListening', 'fire', 'delegate', 'stopDelegating',
258
+ '_addEventListener', '_removeEventListener'
259
+ ]).forEach(key => {
260
+ EmitterMixin[key] = Emitter.prototype[key];
261
+ });
490
262
  /**
491
263
  * Checks if `listeningEmitter` listens to an emitter with given `listenedToEmitterId` and if so, returns that emitter.
492
264
  * If not, returns `null`.
493
265
  *
266
+ * @internal
494
267
  * @protected
495
268
  * @param {module:utils/emittermixin~Emitter} listeningEmitter An emitter that listens.
496
269
  * @param {String} listenedToEmitterId Unique emitter id of emitter listened to.
497
270
  * @returns {module:utils/emittermixin~Emitter|null}
498
271
  */
499
- export function _getEmitterListenedTo( listeningEmitter, listenedToEmitterId ) {
500
- if ( listeningEmitter[ _listeningTo ] && listeningEmitter[ _listeningTo ][ listenedToEmitterId ] ) {
501
- return listeningEmitter[ _listeningTo ][ listenedToEmitterId ].emitter;
502
- }
503
-
504
- return null;
272
+ export function _getEmitterListenedTo(listeningEmitter, listenedToEmitterId) {
273
+ const listeningTo = listeningEmitter[_listeningTo];
274
+ if (listeningTo && listeningTo[listenedToEmitterId]) {
275
+ return listeningTo[listenedToEmitterId].emitter;
276
+ }
277
+ return null;
505
278
  }
506
-
507
279
  /**
508
280
  * Sets emitter's unique id.
509
281
  *
510
282
  * **Note:** `_emitterId` can be set only once.
511
283
  *
284
+ * @internal
512
285
  * @protected
513
286
  * @param {module:utils/emittermixin~Emitter} emitter An emitter for which id will be set.
514
287
  * @param {String} [id] Unique id to set. If not passed, random unique id will be set.
515
288
  */
516
- export function _setEmitterId( emitter, id ) {
517
- if ( !emitter[ _emitterId ] ) {
518
- emitter[ _emitterId ] = id || uid();
519
- }
289
+ export function _setEmitterId(emitter, id) {
290
+ if (!emitter[_emitterId]) {
291
+ emitter[_emitterId] = id || uid();
292
+ }
520
293
  }
521
-
522
294
  /**
523
295
  * Returns emitter's unique id.
524
296
  *
297
+ * @internal
525
298
  * @protected
526
299
  * @param {module:utils/emittermixin~Emitter} emitter An emitter which id will be returned.
300
+ * @returns {String|undefined}
527
301
  */
528
- export function _getEmitterId( emitter ) {
529
- return emitter[ _emitterId ];
302
+ export function _getEmitterId(emitter) {
303
+ return emitter[_emitterId];
530
304
  }
531
-
532
305
  // Gets the internal `_events` property of the given object.
533
306
  // `_events` property store all lists with callbacks for registered event names.
534
307
  // If there were no events registered on the object, empty `_events` object is created.
535
- function getEvents( source ) {
536
- if ( !source._events ) {
537
- Object.defineProperty( source, '_events', {
538
- value: {}
539
- } );
540
- }
541
-
542
- return source._events;
308
+ function getEvents(source) {
309
+ if (!source._events) {
310
+ Object.defineProperty(source, '_events', {
311
+ value: {}
312
+ });
313
+ }
314
+ return source._events;
543
315
  }
544
-
545
316
  // Creates event node for generic-specific events relation architecture.
546
317
  function makeEventNode() {
547
- return {
548
- callbacks: [],
549
- childEvents: []
550
- };
318
+ return {
319
+ callbacks: [],
320
+ childEvents: []
321
+ };
551
322
  }
552
-
553
323
  // Creates an architecture for generic-specific events relation.
554
324
  // If needed, creates all events for given eventName, i.e. if the first registered event
555
325
  // is foo:bar:abc, it will create foo:bar:abc, foo:bar and foo event and tie them together.
556
326
  // It also copies callbacks from more generic events to more specific events when
557
327
  // specific events are created.
558
- function createEventNamespace( source, eventName ) {
559
- const events = getEvents( source );
560
-
561
- // First, check if the event we want to add to the structure already exists.
562
- if ( events[ eventName ] ) {
563
- // If it exists, we don't have to do anything.
564
- return;
565
- }
566
-
567
- // In other case, we have to create the structure for the event.
568
- // Note, that we might need to create intermediate events too.
569
- // I.e. if foo:bar:abc is being registered and we only have foo in the structure,
570
- // we need to also register foo:bar.
571
-
572
- // Currently processed event name.
573
- let name = eventName;
574
- // Name of the event that is a child event for currently processed event.
575
- let childEventName = null;
576
-
577
- // Array containing all newly created specific events.
578
- const newEventNodes = [];
579
-
580
- // While loop can't check for ':' index because we have to handle generic events too.
581
- // In each loop, we truncate event name, going from the most specific name to the generic one.
582
- // I.e. foo:bar:abc -> foo:bar -> foo.
583
- while ( name !== '' ) {
584
- if ( events[ name ] ) {
585
- // If the currently processed event name is already registered, we can be sure
586
- // that it already has all the structure created, so we can break the loop here
587
- // as no more events need to be registered.
588
- break;
589
- }
590
-
591
- // If this event is not yet registered, create a new object for it.
592
- events[ name ] = makeEventNode();
593
- // Add it to the array with newly created events.
594
- newEventNodes.push( events[ name ] );
595
-
596
- // Add previously processed event name as a child of this event.
597
- if ( childEventName ) {
598
- events[ name ].childEvents.push( childEventName );
599
- }
600
-
601
- childEventName = name;
602
- // If `.lastIndexOf()` returns -1, `.substr()` will return '' which will break the loop.
603
- name = name.substr( 0, name.lastIndexOf( ':' ) );
604
- }
605
-
606
- if ( name !== '' ) {
607
- // If name is not empty, we found an already registered event that was a parent of the
608
- // event we wanted to register.
609
-
610
- // Copy that event's callbacks to newly registered events.
611
- for ( const node of newEventNodes ) {
612
- node.callbacks = events[ name ].callbacks.slice();
613
- }
614
-
615
- // Add last newly created event to the already registered event.
616
- events[ name ].childEvents.push( childEventName );
617
- }
328
+ function createEventNamespace(source, eventName) {
329
+ const events = getEvents(source);
330
+ // First, check if the event we want to add to the structure already exists.
331
+ if (events[eventName]) {
332
+ // If it exists, we don't have to do anything.
333
+ return;
334
+ }
335
+ // In other case, we have to create the structure for the event.
336
+ // Note, that we might need to create intermediate events too.
337
+ // I.e. if foo:bar:abc is being registered and we only have foo in the structure,
338
+ // we need to also register foo:bar.
339
+ // Currently processed event name.
340
+ let name = eventName;
341
+ // Name of the event that is a child event for currently processed event.
342
+ let childEventName = null;
343
+ // Array containing all newly created specific events.
344
+ const newEventNodes = [];
345
+ // While loop can't check for ':' index because we have to handle generic events too.
346
+ // In each loop, we truncate event name, going from the most specific name to the generic one.
347
+ // I.e. foo:bar:abc -> foo:bar -> foo.
348
+ while (name !== '') {
349
+ if (events[name]) {
350
+ // If the currently processed event name is already registered, we can be sure
351
+ // that it already has all the structure created, so we can break the loop here
352
+ // as no more events need to be registered.
353
+ break;
354
+ }
355
+ // If this event is not yet registered, create a new object for it.
356
+ events[name] = makeEventNode();
357
+ // Add it to the array with newly created events.
358
+ newEventNodes.push(events[name]);
359
+ // Add previously processed event name as a child of this event.
360
+ if (childEventName) {
361
+ events[name].childEvents.push(childEventName);
362
+ }
363
+ childEventName = name;
364
+ // If `.lastIndexOf()` returns -1, `.substr()` will return '' which will break the loop.
365
+ name = name.substr(0, name.lastIndexOf(':'));
366
+ }
367
+ if (name !== '') {
368
+ // If name is not empty, we found an already registered event that was a parent of the
369
+ // event we wanted to register.
370
+ // Copy that event's callbacks to newly registered events.
371
+ for (const node of newEventNodes) {
372
+ node.callbacks = events[name].callbacks.slice();
373
+ }
374
+ // Add last newly created event to the already registered event.
375
+ events[name].childEvents.push(childEventName);
376
+ }
618
377
  }
619
-
620
378
  // Gets an array containing callbacks list for a given event and it's more specific events.
621
379
  // I.e. if given event is foo:bar and there is also foo:bar:abc event registered, this will
622
380
  // return callback list of foo:bar and foo:bar:abc (but not foo).
623
- function getCallbacksListsForNamespace( source, eventName ) {
624
- const eventNode = getEvents( source )[ eventName ];
625
-
626
- if ( !eventNode ) {
627
- return [];
628
- }
629
-
630
- let callbacksLists = [ eventNode.callbacks ];
631
-
632
- for ( let i = 0; i < eventNode.childEvents.length; i++ ) {
633
- const childCallbacksLists = getCallbacksListsForNamespace( source, eventNode.childEvents[ i ] );
634
-
635
- callbacksLists = callbacksLists.concat( childCallbacksLists );
636
- }
637
-
638
- return callbacksLists;
381
+ function getCallbacksListsForNamespace(source, eventName) {
382
+ const eventNode = getEvents(source)[eventName];
383
+ if (!eventNode) {
384
+ return [];
385
+ }
386
+ let callbacksLists = [eventNode.callbacks];
387
+ for (let i = 0; i < eventNode.childEvents.length; i++) {
388
+ const childCallbacksLists = getCallbacksListsForNamespace(source, eventNode.childEvents[i]);
389
+ callbacksLists = callbacksLists.concat(childCallbacksLists);
390
+ }
391
+ return callbacksLists;
639
392
  }
640
-
641
393
  // Get the list of callbacks for a given event, but only if there any callbacks have been registered.
642
394
  // If there are no callbacks registered for given event, it checks if this is a specific event and looks
643
395
  // for callbacks for it's more generic version.
644
- function getCallbacksForEvent( source, eventName ) {
645
- let event;
646
-
647
- if ( !source._events || !( event = source._events[ eventName ] ) || !event.callbacks.length ) {
648
- // There are no callbacks registered for specified eventName.
649
- // But this could be a specific-type event that is in a namespace.
650
- if ( eventName.indexOf( ':' ) > -1 ) {
651
- // If the eventName is specific, try to find callback lists for more generic event.
652
- return getCallbacksForEvent( source, eventName.substr( 0, eventName.lastIndexOf( ':' ) ) );
653
- } else {
654
- // If this is a top-level generic event, return null;
655
- return null;
656
- }
657
- }
658
-
659
- return event.callbacks;
396
+ function getCallbacksForEvent(source, eventName) {
397
+ let event;
398
+ if (!source._events || !(event = source._events[eventName]) || !event.callbacks.length) {
399
+ // There are no callbacks registered for specified eventName.
400
+ // But this could be a specific-type event that is in a namespace.
401
+ if (eventName.indexOf(':') > -1) {
402
+ // If the eventName is specific, try to find callback lists for more generic event.
403
+ return getCallbacksForEvent(source, eventName.substr(0, eventName.lastIndexOf(':')));
404
+ }
405
+ else {
406
+ // If this is a top-level generic event, return null;
407
+ return null;
408
+ }
409
+ }
410
+ return event.callbacks;
660
411
  }
661
-
662
412
  // Fires delegated events for given map of destinations.
663
413
  //
664
414
  // @private
@@ -666,54 +416,38 @@ function getCallbacksForEvent( source, eventName ) {
666
416
  // `[ {@link module:utils/emittermixin~Emitter}, "event name" ]` pair destinations.
667
417
  // * @param {utils.EventInfo} eventInfo The original event info object.
668
418
  // * @param {Array.<*>} fireArgs Arguments the original event was fired with.
669
- function fireDelegatedEvents( destinations, eventInfo, fireArgs ) {
670
- for ( let [ emitter, name ] of destinations ) {
671
- if ( !name ) {
672
- name = eventInfo.name;
673
- } else if ( typeof name == 'function' ) {
674
- name = name( eventInfo.name );
675
- }
676
-
677
- const delegatedInfo = new EventInfo( eventInfo.source, name );
678
-
679
- delegatedInfo.path = [ ...eventInfo.path ];
680
-
681
- emitter.fire( delegatedInfo, ...fireArgs );
682
- }
419
+ function fireDelegatedEvents(destinations, eventInfo, fireArgs) {
420
+ for (let [emitter, name] of destinations) {
421
+ if (!name) {
422
+ name = eventInfo.name;
423
+ }
424
+ else if (typeof name == 'function') {
425
+ name = name(eventInfo.name);
426
+ }
427
+ const delegatedInfo = new EventInfo(eventInfo.source, name);
428
+ delegatedInfo.path = [...eventInfo.path];
429
+ emitter.fire(delegatedInfo, ...fireArgs);
430
+ }
683
431
  }
684
-
685
432
  // Helper for registering event callback on the emitter.
686
- function addEventListener( listener, emitter, event, callback, options ) {
687
- if ( emitter._addEventListener ) {
688
- emitter._addEventListener( event, callback, options );
689
- } else {
690
- // Allow listening on objects that do not implement Emitter interface.
691
- // This is needed in some tests that are using mocks instead of the real objects with EmitterMixin mixed.
692
- listener._addEventListener.call( emitter, event, callback, options );
693
- }
433
+ function addEventListener(listener, emitter, event, callback, options) {
434
+ if (emitter._addEventListener) {
435
+ emitter._addEventListener(event, callback, options);
436
+ }
437
+ else {
438
+ // Allow listening on objects that do not implement Emitter interface.
439
+ // This is needed in some tests that are using mocks instead of the real objects with EmitterMixin mixed.
440
+ (listener._addEventListener).call(emitter, event, callback, options);
441
+ }
694
442
  }
695
-
696
443
  // Helper for removing event callback from the emitter.
697
- function removeEventListener( listener, emitter, event, callback ) {
698
- if ( emitter._removeEventListener ) {
699
- emitter._removeEventListener( event, callback );
700
- } else {
701
- // Allow listening on objects that do not implement Emitter interface.
702
- // This is needed in some tests that are using mocks instead of the real objects with EmitterMixin mixed.
703
- listener._removeEventListener.call( emitter, event, callback );
704
- }
444
+ function removeEventListener(listener, emitter, event, callback) {
445
+ if (emitter._removeEventListener) {
446
+ emitter._removeEventListener(event, callback);
447
+ }
448
+ else {
449
+ // Allow listening on objects that do not implement Emitter interface.
450
+ // This is needed in some tests that are using mocks instead of the real objects with EmitterMixin mixed.
451
+ listener._removeEventListener.call(emitter, event, callback);
452
+ }
705
453
  }
706
-
707
- /**
708
- * The return value of {@link ~EmitterMixin#delegate}.
709
- *
710
- * @interface module:utils/emittermixin~EmitterMixinDelegateChain
711
- */
712
-
713
- /**
714
- * Selects destination for {@link module:utils/emittermixin~EmitterMixin#delegate} events.
715
- *
716
- * @method #to
717
- * @param {module:utils/emittermixin~Emitter} emitter An `EmitterMixin` instance which is the destination for delegated events.
718
- * @param {String|Function} [nameOrFunction] A custom event name or function which converts the original name string.
719
- */