Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ve.EventSequencer.js

raw symbols SCIP
1 /*!
2 * VisualEditor EventSequencer class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * EventSequencer class with on-event and after-event listeners.
9 *
10 * After-event listeners are fired as soon as possible after the
11 * corresponding native event. They are similar to the setTimeout(f, 0)
12 * idiom, except that they are guaranteed to execute before any subsequent
13 * on-event listener. Therefore, events are executed in the 'right order'.
14 *
15 * This matters when many events are added to the task queue in one go.
16 * For instance, browsers often queue 'keydown' and 'keypress' in immediate
17 * sequence, so a setTimeout(f, 0) defined in the keydown listener will run
18 * **after** the keypress listener (i.e. in the 'wrong' order). EventSequencer
19 * ensures that this does not happen.
20 *
21 * All these listeners receive the jQuery event as an argument. If an on-event
22 * listener needs to pass information to a corresponding after-event listener,
23 * it can do so by adding properties into the jQuery event itself.
24 *
25 * There are also 'onLoop' and 'afterLoop' listeners, which only fire once per
26 * Javascript event loop iteration, respectively before and after all the
27 * other listeners fire.
28 *
29 * There is special handling for sequences (keydown,keypress), where the
30 * keypress handler is called before the native keydown action happens. In
31 * this case, after-keydown handlers fire after on-keypress handlers.
32 *
33 * For further event loop / task queue information, see:
34 * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-loops
35 *
36 * @class ve.EventSequencer
37 */
38
39 /**
40 * To fire after-event listeners promptly, the EventSequencer may need to
41 * listen to some events for which it has no registered on-event or
42 * after-event listeners. For instance, to ensure an after-keydown listener
43 * is be fired before the native keyup action, you must include both
44 * 'keydown' and 'keyup' in the eventNames Array.
45 *
46 * @constructor
47 * @param {string[]} eventNames List of event Names to listen to
48 */
49 ve.EventSequencer = function VeEventSequencer( eventNames ) {
50 this.$node = null;
51 this.eventNames = eventNames;
52 this.eventHandlers = {};
53
54 /**
55 * Generate an event handler for a specific event
56 *
57 * @private
58 * @param {string} name The event's name
59 * @return {Function} An event handler
60 */
61 const makeEventHandler = ( name ) => ( ev ) => this.onEvent( name, ev );
62
63 /**
64 * @property {Object[]} Pending calls
65 * - id {number} Id for setTimeout
66 * - func {Function} Post-event listener
67 * - ev {jQuery.Event} Browser event
68 * - eventName {string} Name, such as keydown
69 */
70 this.pendingCalls = [];
71
72 /**
73 * @property {Object.<string,Function[]>}
74 */
75 this.onListenersForEvent = {};
76
77 /**
78 * @property {Object.<string,Function[]>}
79 */
80 this.afterListenersForEvent = {};
81
82 /**
83 * @property {Object.<string,Function[]>}
84 */
85 this.afterOneListenersForEvent = {};
86
87 for ( let i = 0, len = eventNames.length; i < len; i++ ) {
88 const eventName = eventNames[ i ];
89 this.onListenersForEvent[ eventName ] = [];
90 this.afterListenersForEvent[ eventName ] = [];
91 this.afterOneListenersForEvent[ eventName ] = [];
92 this.eventHandlers[ eventName ] = makeEventHandler( eventName );
93 }
94
95 /**
96 * @property {Function[]}
97 */
98 this.onLoopListeners = [];
99
100 /**
101 * @property {Function[]}
102 */
103 this.afterLoopListeners = [];
104
105 /**
106 * @property {Function[]}
107 */
108 this.afterLoopOneListeners = [];
109
110 /**
111 * @property {boolean}
112 */
113 this.doneOnLoop = false;
114
115 /**
116 * @property {number}
117 */
118 this.afterLoopTimeoutId = null;
119 };
120
121 /**
122 * Attach to a node, to listen to its jQuery events
123 *
124 * @param {jQuery} $node The node to attach to
125 * @return {ve.EventSequencer}
126 * @chainable
127 */
128 ve.EventSequencer.prototype.attach = function ( $node ) {
129 this.detach();
130 this.$node = $node.on( this.eventHandlers );
131 return this;
132 };
133
134 // eslint-disable-next-line jsdoc/require-returns-check
135 /**
136 * Detach from a node (if attached), to stop listen to its jQuery events
137 *
138 * @return {ve.EventSequencer}
139 * @chainable
140 */
141 ve.EventSequencer.prototype.detach = function () {
142 if ( this.$node === null ) {
143 return;
144 }
145 this.runPendingCalls();
146 this.$node.off( this.eventHandlers );
147 this.$node = null;
148 return this;
149 };
150
151 /**
152 * Add listeners to be fired at the start of the Javascript event loop iteration
153 *
154 * @param {Function|Function[]} listeners Listener(s) that take no arguments
155 * @return {ve.EventSequencer}
156 * @chainable
157 */
158 ve.EventSequencer.prototype.onLoop = function ( listeners ) {
159 if ( !Array.isArray( listeners ) ) {
160 listeners = [ listeners ];
161 }
162 ve.batchPush( this.onLoopListeners, listeners );
163 return this;
164 };
165
166 /**
167 * Add listeners to be fired just before the browser native action
168 *
169 * @param {Object.<string,Function>} listeners Function for each event
170 * @return {ve.EventSequencer}
171 * @chainable
172 */
173 ve.EventSequencer.prototype.on = function ( listeners ) {
174 for ( const eventName in listeners ) {
175 this.onListenersForEvent[ eventName ].push( listeners[ eventName ] );
176 }
177 return this;
178 };
179
180 /**
181 * Add listeners to be fired as soon as possible after the native action
182 *
183 * @param {Object.<string,Function>} listeners Function for each event
184 * @return {ve.EventSequencer}
185 * @chainable
186 */
187 ve.EventSequencer.prototype.after = function ( listeners ) {
188 for ( const eventName in listeners ) {
189 this.afterListenersForEvent[ eventName ].push( listeners[ eventName ] );
190 }
191 return this;
192 };
193
194 /**
195 * Add listeners to be fired once, as soon as possible after the native action
196 *
197 * @param {Object.<string,Function[]>} listeners Function for each event
198 * @return {ve.EventSequencer}
199 * @chainable
200 */
201 ve.EventSequencer.prototype.afterOne = function ( listeners ) {
202 for ( const eventName in listeners ) {
203 this.afterOneListenersForEvent[ eventName ].push( listeners[ eventName ] );
204 }
205 return this;
206 };
207
208 /**
209 * Add listeners to be fired at the end of the Javascript event loop iteration
210 *
211 * @param {Function|Function[]} listeners Listener(s) that take no arguments
212 * @return {ve.EventSequencer}
213 * @chainable
214 */
215 ve.EventSequencer.prototype.afterLoop = function ( listeners ) {
216 if ( !Array.isArray( listeners ) ) {
217 listeners = [ listeners ];
218 }
219 ve.batchPush( this.afterLoopListeners, listeners );
220 return this;
221 };
222
223 /**
224 * Add listeners to be fired once, at the end of the Javascript event loop iteration
225 *
226 * @param {Function|Function[]} listeners Listener(s) that take no arguments
227 * @return {ve.EventSequencer}
228 * @chainable
229 */
230 ve.EventSequencer.prototype.afterLoopOne = function ( listeners ) {
231 if ( !Array.isArray( listeners ) ) {
232 listeners = [ listeners ];
233 }
234 ve.batchPush( this.afterLoopOneListeners, listeners );
235 return this;
236 };
237
238 /**
239 * Generic listener method which does the sequencing
240 *
241 * @private
242 * @param {string} eventName Javascript name of the event, e.g. 'keydown'
243 * @param {jQuery.Event} ev The browser event
244 */
245 ve.EventSequencer.prototype.onEvent = function ( eventName, ev ) {
246 this.runPendingCalls( eventName );
247 if ( !this.doneOnLoop ) {
248 this.doneOnLoop = true;
249 this.doOnLoop();
250 }
251
252 // Listener list: take snapshot (for immutability if a listener adds another listener)
253 const onListeners = ( this.onListenersForEvent[ eventName ] || [] ).slice();
254
255 for ( let i = 0, len = onListeners.length; i < len; i++ ) {
256 const onListener = onListeners[ i ];
257 this.callListener( 'on', eventName, i, onListener, ev );
258 }
259 // Create a cancellable pending call. We need one even if there are no after*Listeners, to
260 // call resetAfterLoopTimeout which resets doneOneLoop to false.
261 // - Create the pendingCall object first
262 // - then create the setTimeout invocation to modify pendingCall.id
263 // - then set pendingCall.id to the setTimeout id, so the call can cancel itself
264 const pendingCall = { id: null, ev: ev, eventName: eventName };
265 const id = this.postpone( () => {
266 if ( pendingCall.id === null ) {
267 // clearTimeout seems not always to work immediately
268 return;
269 }
270 this.resetAfterLoopTimeout();
271 pendingCall.id = null;
272 this.afterEvent( eventName, ev );
273 } );
274 pendingCall.id = id;
275 this.pendingCalls.push( pendingCall );
276 };
277
278 /**
279 * Generic after listener method which gets queued
280 *
281 * @private
282 * @param {string} eventName Javascript name of the event, e.g. 'keydown'
283 * @param {jQuery.Event} ev The browser event
284 */
285 ve.EventSequencer.prototype.afterEvent = function ( eventName, ev ) {
286 // Listener list: take snapshot (for immutability if a listener adds another listener)
287 const afterListeners = ( this.afterListenersForEvent[ eventName ] || [] ).slice();
288 // One-time listener list: take snapshot (for immutability) and blank the list
289 const afterOneListeners = ( this.afterOneListenersForEvent[ eventName ] || [] ).splice( 0 );
290
291 for ( let i = 0, len = afterListeners.length; i < len; i++ ) {
292 this.callListener( 'after', eventName, i, afterListeners[ i ], ev );
293 }
294
295 for ( let i = 0, len = afterOneListeners.length; i < len; i++ ) {
296 this.callListener( 'afterOne', eventName, i, afterOneListeners[ i ], ev );
297 }
298 };
299
300 /**
301 * Call each onLoopListener once
302 *
303 * @private
304 */
305 ve.EventSequencer.prototype.doOnLoop = function () {
306 // Length cache 'len' is required, as the functions called may add another listener
307 for ( let i = 0, len = this.onLoopListeners.length; i < len; i++ ) {
308 this.callListener( 'onLoop', null, i, this.onLoopListeners[ i ], null );
309 }
310 };
311
312 /**
313 * Call each afterLoopListener once, unless the setTimeout is already cancelled
314 *
315 * @private
316 * @param {number} myTimeoutId The calling setTimeout id
317 */
318 ve.EventSequencer.prototype.doAfterLoop = function ( myTimeoutId ) {
319 if ( this.afterLoopTimeoutId !== myTimeoutId ) {
320 // Cancelled; do nothing
321 return;
322 }
323 this.afterLoopTimeoutId = null;
324
325 // Loop listener list: take snapshot (for immutability if a listener adds another listener)
326 const afterLoopListeners = this.afterLoopListeners.slice();
327 // One-time loop listener list: take snapshot (for immutability) and blank the list
328 const afterLoopOneListeners = this.afterLoopOneListeners.splice( 0 );
329
330 for ( let i = 0, len = afterLoopListeners.length; i < len; i++ ) {
331 this.callListener( 'afterLoop', null, i, this.afterLoopListeners[ i ], null );
332 }
333
334 for ( let i = 0, len = afterLoopOneListeners.length; i < len; i++ ) {
335 this.callListener( 'afterLoopOne', null, i, afterLoopOneListeners[ i ], null );
336 }
337 this.doneOnLoop = false;
338 };
339
340 /**
341 * Push any pending doAfterLoop to end of task queue (cancel, then re-set)
342 *
343 * @private
344 */
345 ve.EventSequencer.prototype.resetAfterLoopTimeout = function () {
346 if ( this.afterLoopTimeoutId !== null ) {
347 this.cancelPostponed( this.afterLoopTimeoutId );
348 }
349 const timeoutId = this.postpone( () => {
350 this.doAfterLoop( timeoutId );
351 } );
352 this.afterLoopTimeoutId = timeoutId;
353 };
354
355 /**
356 * Run any pending listeners, and clear the pending queue
357 *
358 * @private
359 * @param {string} eventName The name of the event currently being triggered
360 */
361 ve.EventSequencer.prototype.runPendingCalls = function ( eventName ) {
362 const afterKeyDownCalls = [];
363
364 for ( let i = 0; i < this.pendingCalls.length; i++ ) {
365 // Length cache not possible, as a pending call appends another pending call.
366 // It's important that this list remains mutable, in the case that this
367 // function indirectly recurses.
368 const pendingCall = this.pendingCalls[ i ];
369 if ( pendingCall.id === null ) {
370 // The call has already run
371 continue;
372 }
373 if ( eventName === 'keypress' && pendingCall.eventName === 'keydown' ) {
374 // Delay afterKeyDown till after keypress
375 afterKeyDownCalls.push( pendingCall );
376 continue;
377 }
378
379 this.cancelPostponed( pendingCall.id );
380 pendingCall.id = null;
381 // Force to run now. It's important that we set id to null before running,
382 // so that there's no chance a recursive call will call the listener again.
383 this.afterEvent( pendingCall.eventName, pendingCall.ev );
384 }
385 // This is safe: we only ever appended to the list, so it's definitely exhausted now.
386 this.pendingCalls.length = 0;
387 this.pendingCalls.push.apply( this.pendingCalls, afterKeyDownCalls );
388 };
389
390 /**
391 * Make a postponed call.
392 *
393 * This is a separate function because that makes it easier to replace when testing
394 *
395 * @param {Function} callback The function to call
396 * @return {number} Unique postponed timeout id
397 */
398 ve.EventSequencer.prototype.postpone = function ( callback ) {
399 return setTimeout( callback );
400 };
401
402 /**
403 * Cancel a postponed call.
404 *
405 * This is a separate function because that makes it easier to replace when testing
406 *
407 * @param {number} timeoutId Unique postponed timeout id
408 */
409 ve.EventSequencer.prototype.cancelPostponed = function ( timeoutId ) {
410 clearTimeout( timeoutId );
411 };
412
413 /**
414 * Single method to perform all listener calls, for ease of debugging
415 *
416 * @param {string} timing on|after|afterOne|onLoop|afterLoop|afterLoopOne
417 * @param {string} eventName Name of the event
418 * @param {number} i The sequence of the listener
419 * @param {Function} listener The listener to call
420 * @param {jQuery.Event} ev The browser event
421 */
422 ve.EventSequencer.prototype.callListener = function ( timing, eventName, i, listener, ev ) {
423 listener( ev );
424 };