Debian Codegraph @

packages/signaling/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 /**
11 * @packageDocumentation
12 * @module signaling
13 */
14 import { ArrayExt, find } from '@lumino/algorithm';
15 import { PromiseDelegate } from '@lumino/coreutils';
16
17 /**
18 * A type alias for a slot function.
19 *
20 * @param sender - The object emitting the signal.
21 *
22 * @param args - The args object emitted with the signal.
23 *
24 * #### Notes
25 * A slot is invoked when a signal to which it is connected is emitted.
26 */
27 export type Slot<T, U> = (sender: T, args: U) => void;
28
29 /**
30 * An object used for type-safe inter-object communication.
31 *
32 * #### Notes
33 * Signals provide a type-safe implementation of the publish-subscribe
34 * pattern. An object (publisher) declares which signals it will emit,
35 * and consumers connect callbacks (subscribers) to those signals. The
36 * subscribers are invoked whenever the publisher emits the signal.
37 */
38 export interface ISignal<T, U> {
39 /**
40 * Connect a slot to the signal.
41 *
42 * @param slot - The slot to invoke when the signal is emitted.
43 *
44 * @param thisArg - The `this` context for the slot. If provided,
45 * this must be a non-primitive object.
46 *
47 * @returns `true` if the connection succeeds, `false` otherwise.
48 *
49 * #### Notes
50 * Slots are invoked in the order in which they are connected.
51 *
52 * Signal connections are unique. If a connection already exists for
53 * the given `slot` and `thisArg`, this method returns `false`.
54 *
55 * A newly connected slot will not be invoked until the next time the
56 * signal is emitted, even if the slot is connected while the signal
57 * is dispatching.
58 */
59 connect(slot: Slot<T, U>, thisArg?: any): boolean;
60
61 /**
62 * Disconnect a slot from the signal.
63 *
64 * @param slot - The slot to disconnect from the signal.
65 *
66 * @param thisArg - The `this` context for the slot. If provided,
67 * this must be a non-primitive object.
68 *
69 * @returns `true` if the connection is removed, `false` otherwise.
70 *
71 * #### Notes
72 * If no connection exists for the given `slot` and `thisArg`, this
73 * method returns `false`.
74 *
75 * A disconnected slot will no longer be invoked, even if the slot
76 * is disconnected while the signal is dispatching.
77 */
78 disconnect(slot: Slot<T, U>, thisArg?: any): boolean;
79 }
80
81 /**
82 * An object that is both a signal and an async iterable.
83 */
84 export interface IStream<T, U> extends ISignal<T, U>, AsyncIterable<U> {}
85
86 /**
87 * A concrete implementation of `ISignal`.
88 *
89 * #### Example
90 * ```typescript
91 * import { ISignal, Signal } from '@lumino/signaling';
92 *
93 * class SomeClass {
94 *
95 * constructor(name: string) {
96 * this.name = name;
97 * }
98 *
99 * readonly name: string;
100 *
101 * get valueChanged: ISignal<this, number> {
102 * return this._valueChanged;
103 * }
104 *
105 * get value(): number {
106 * return this._value;
107 * }
108 *
109 * set value(value: number) {
110 * if (value === this._value) {
111 * return;
112 * }
113 * this._value = value;
114 * this._valueChanged.emit(value);
115 * }
116 *
117 * private _value = 0;
118 * private _valueChanged = new Signal<this, number>(this);
119 * }
120 *
121 * function logger(sender: SomeClass, value: number): void {
122 * console.log(sender.name, value);
123 * }
124 *
125 * let m1 = new SomeClass('foo');
126 * let m2 = new SomeClass('bar');
127 *
128 * m1.valueChanged.connect(logger);
129 * m2.valueChanged.connect(logger);
130 *
131 * m1.value = 42; // logs: foo 42
132 * m2.value = 17; // logs: bar 17
133 * ```
134 */
135 export class Signal<T, U> implements ISignal<T, U> {
136 /**
137 * Construct a new signal.
138 *
139 * @param sender - The sender which owns the signal.
140 */
141 constructor(sender: T) {
142 this.sender = sender;
143 }
144
145 /**
146 * The sender which owns the signal.
147 */
148 readonly sender: T;
149
150 /**
151 * Connect a slot to the signal.
152 *
153 * @param slot - The slot to invoke when the signal is emitted.
154 *
155 * @param thisArg - The `this` context for the slot. If provided,
156 * this must be a non-primitive object.
157 *
158 * @returns `true` if the connection succeeds, `false` otherwise.
159 */
160 connect(slot: Slot<T, U>, thisArg?: unknown): boolean {
161 return Private.connect(this, slot, thisArg);
162 }
163
164 /**
165 * Disconnect a slot from the signal.
166 *
167 * @param slot - The slot to disconnect from the signal.
168 *
169 * @param thisArg - The `this` context for the slot. If provided,
170 * this must be a non-primitive object.
171 *
172 * @returns `true` if the connection is removed, `false` otherwise.
173 */
174 disconnect(slot: Slot<T, U>, thisArg?: unknown): boolean {
175 return Private.disconnect(this, slot, thisArg);
176 }
177
178 /**
179 * Emit the signal and invoke the connected slots.
180 *
181 * @param args - The args to pass to the connected slots.
182 *
183 * #### Notes
184 * Slots are invoked synchronously in connection order.
185 *
186 * Exceptions thrown by connected slots will be caught and logged.
187 */
188 emit(args: U): void {
189 Private.emit(this, args);
190 }
191 }
192
193 /**
194 * The namespace for the `Signal` class statics.
195 */
196 export namespace Signal {
197 /**
198 * Remove all connections between a sender and receiver.
199 *
200 * @param sender - The sender object of interest.
201 *
202 * @param receiver - The receiver object of interest.
203 *
204 * #### Notes
205 * If a `thisArg` is provided when connecting a signal, that object
206 * is considered the receiver. Otherwise, the `slot` is considered
207 * the receiver.
208 */
209 export function disconnectBetween(sender: unknown, receiver: unknown): void {
210 Private.disconnectBetween(sender, receiver);
211 }
212
213 /**
214 * Remove all connections where the given object is the sender.
215 *
216 * @param sender - The sender object of interest.
217 */
218 export function disconnectSender(sender: unknown): void {
219 Private.disconnectSender(sender);
220 }
221
222 /**
223 * Remove all connections where the given object is the receiver.
224 *
225 * @param receiver - The receiver object of interest.
226 *
227 * #### Notes
228 * If a `thisArg` is provided when connecting a signal, that object
229 * is considered the receiver. Otherwise, the `slot` is considered
230 * the receiver.
231 */
232 export function disconnectReceiver(receiver: unknown): void {
233 Private.disconnectReceiver(receiver);
234 }
235
236 /**
237 * Remove all connections where an object is the sender or receiver.
238 *
239 * @param object - The object of interest.
240 *
241 * #### Notes
242 * If a `thisArg` is provided when connecting a signal, that object
243 * is considered the receiver. Otherwise, the `slot` is considered
244 * the receiver.
245 */
246 export function disconnectAll(object: unknown): void {
247 Private.disconnectAll(object);
248 }
249
250 /**
251 * Clear all signal data associated with the given object.
252 *
253 * @param object - The object for which the data should be cleared.
254 *
255 * #### Notes
256 * This removes all signal connections and any other signal data
257 * associated with the object.
258 */
259 export function clearData(object: unknown): void {
260 Private.disconnectAll(object);
261 }
262
263 /**
264 * A type alias for the exception handler function.
265 */
266 export type ExceptionHandler = (err: Error) => void;
267
268 /**
269 * Get the signal exception handler.
270 *
271 * @returns The current exception handler.
272 *
273 * #### Notes
274 * The default exception handler is `console.error`.
275 */
276 export function getExceptionHandler(): ExceptionHandler {
277 return Private.exceptionHandler;
278 }
279
280 /**
281 * Set the signal exception handler.
282 *
283 * @param handler - The function to use as the exception handler.
284 *
285 * @returns The old exception handler.
286 *
287 * #### Notes
288 * The exception handler is invoked when a slot throws an exception.
289 */
290 export function setExceptionHandler(
291 handler: ExceptionHandler
292 ): ExceptionHandler {
293 let old = Private.exceptionHandler;
294 Private.exceptionHandler = handler;
295 return old;
296 }
297 }
298
299 /**
300 * A concrete implementation of `IStream`.
301 *
302 * #### Example
303 * ```typescript
304 * import { IStream, Stream } from '@lumino/signaling';
305 *
306 * class SomeClass {
307 *
308 * constructor(name: string) {
309 * this.name = name;
310 * }
311 *
312 * readonly name: string;
313 *
314 * get pings(): IStream<this, string> {
315 * return this._pings;
316 * }
317 *
318 * ping(value: string) {
319 * this._pings.emit(value);
320 * }
321 *
322 * private _pings = new Stream<this, string>(this);
323 * }
324 *
325 * let m1 = new SomeClass('foo');
326 *
327 * m1.pings.connect((_, value: string) => {
328 * console.log('connect', value);
329 * });
330 *
331 * void (async () => {
332 * for await (const ping of m1.pings) {
333 * console.log('iterator', ping);
334 * }
335 * })();
336 *
337 * m1.ping('alpha'); // logs: connect alpha
338 * // logs: iterator alpha
339 * m1.ping('beta'); // logs: connect beta
340 * // logs: iterator beta
341 * ```
342 */
343 export class Stream<T, U> extends Signal<T, U> implements IStream<T, U> {
344 /**
345 * Return an async iterator that yields every emission.
346 */
347 async *[Symbol.asyncIterator](): AsyncIterableIterator<U> {
348 let pending = this._pending;
349 while (true) {
350 try {
351 const { args, next } = await pending.promise;
352 pending = next;
353 yield args;
354 } catch (_) {
355 return; // Any promise rejection stops the iterator.
356 }
357 }
358 }
359
360 /**
361 * Emit the signal, invoke the connected slots, and yield the emission.
362 *
363 * @param args - The args to pass to the connected slots.
364 */
365 emit(args: U): void {
366 const pending = this._pending;
367 const next = (this._pending = new PromiseDelegate());
368 pending.resolve({ args, next });
369 super.emit(args);
370 }
371
372 /**
373 * Stop the stream's async iteration.
374 */
375 stop(): void {
376 this._pending.promise.catch(() => undefined);
377 this._pending.reject('stop');
378 this._pending = new PromiseDelegate();
379 }
380
381 private _pending: Private.Pending<U> = new PromiseDelegate();
382 }
383
384 /**
385 * The namespace for the module implementation details.
386 */
387 namespace Private {
388 /**
389 * A pending promise in a promise chain underlying a stream.
390 */
391 export type Pending<U> = PromiseDelegate<{ args: U; next: Pending<U> }>;
392
393 /**
394 * The signal exception handler function.
395 */
396 export let exceptionHandler: Signal.ExceptionHandler = (err: Error) => {
397 console.error(err);
398 };
399
400 /**
401 * Connect a slot to a signal.
402 *
403 * @param signal - The signal of interest.
404 *
405 * @param slot - The slot to invoke when the signal is emitted.
406 *
407 * @param thisArg - The `this` context for the slot. If provided,
408 * this must be a non-primitive object.
409 *
410 * @returns `true` if the connection succeeds, `false` otherwise.
411 */
412 export function connect<T, U>(
413 signal: Signal<T, U>,
414 slot: Slot<T, U>,
415 thisArg?: unknown
416 ): boolean {
417 // Coerce a `null` `thisArg` to `undefined`.
418 thisArg = thisArg || undefined;
419
420 // Ensure the sender's array of receivers is created.
421 let receivers = receiversForSender.get(signal.sender);
422 if (!receivers) {
423 receivers = [];
424 receiversForSender.set(signal.sender, receivers);
425 }
426
427 // Bail if a matching connection already exists.
428 if (findConnection(receivers, signal, slot, thisArg)) {
429 return false;
430 }
431
432 // Choose the best object for the receiver.
433 let receiver = thisArg || slot;
434
435 // Ensure the receiver's array of senders is created.
436 let senders = sendersForReceiver.get(receiver);
437 if (!senders) {
438 senders = [];
439 sendersForReceiver.set(receiver, senders);
440 }
441
442 // Create a new connection and add it to the end of each array.
443 let connection = { signal, slot, thisArg };
444 receivers.push(connection);
445 senders.push(connection);
446
447 // Indicate a successful connection.
448 return true;
449 }
450
451 /**
452 * Disconnect a slot from a signal.
453 *
454 * @param signal - The signal of interest.
455 *
456 * @param slot - The slot to disconnect from the signal.
457 *
458 * @param thisArg - The `this` context for the slot. If provided,
459 * this must be a non-primitive object.
460 *
461 * @returns `true` if the connection is removed, `false` otherwise.
462 */
463 export function disconnect<T, U>(
464 signal: Signal<T, U>,
465 slot: Slot<T, U>,
466 thisArg?: unknown
467 ): boolean {
468 // Coerce a `null` `thisArg` to `undefined`.
469 thisArg = thisArg || undefined;
470
471 // Lookup the list of receivers, and bail if none exist.
472 let receivers = receiversForSender.get(signal.sender);
473 if (!receivers || receivers.length === 0) {
474 return false;
475 }
476
477 // Bail if no matching connection exits.
478 let connection = findConnection(receivers, signal, slot, thisArg);
479 if (!connection) {
480 return false;
481 }
482
483 // Choose the best object for the receiver.
484 let receiver = thisArg || slot;
485
486 // Lookup the array of senders, which is now known to exist.
487 let senders = sendersForReceiver.get(receiver)!;
488
489 // Clear the connection and schedule cleanup of the arrays.
490 connection.signal = null;
491 scheduleCleanup(receivers);
492 scheduleCleanup(senders);
493
494 // Indicate a successful disconnection.
495 return true;
496 }
497
498 /**
499 * Remove all connections between a sender and receiver.
500 *
501 * @param sender - The sender object of interest.
502 *
503 * @param receiver - The receiver object of interest.
504 */
505 export function disconnectBetween(sender: unknown, receiver: unknown): void {
506 // If there are no receivers, there is nothing to do.
507 let receivers = receiversForSender.get(sender);
508 if (!receivers || receivers.length === 0) {
509 return;
510 }
511
512 // If there are no senders, there is nothing to do.
513 let senders = sendersForReceiver.get(receiver);
514 if (!senders || senders.length === 0) {
515 return;
516 }
517
518 // Clear each connection between the sender and receiver.
519 for (const connection of senders) {
520 // Skip connections which have already been cleared.
521 if (!connection.signal) {
522 continue;
523 }
524
525 // Clear the connection if it matches the sender.
526 if (connection.signal.sender === sender) {
527 connection.signal = null;
528 }
529 }
530
531 // Schedule a cleanup of the senders and receivers.
532 scheduleCleanup(receivers);
533 scheduleCleanup(senders);
534 }
535
536 /**
537 * Remove all connections where the given object is the sender.
538 *
539 * @param sender - The sender object of interest.
540 */
541 export function disconnectSender(sender: unknown): void {
542 // If there are no receivers, there is nothing to do.
543 let receivers = receiversForSender.get(sender);
544 if (!receivers || receivers.length === 0) {
545 return;
546 }
547
548 // Clear each receiver connection.
549 for (const connection of receivers) {
550 // Skip connections which have already been cleared.
551 if (!connection.signal) {
552 continue;
553 }
554
555 // Choose the best object for the receiver.
556 let receiver = connection.thisArg || connection.slot;
557
558 // Clear the connection.
559 connection.signal = null;
560
561 // Cleanup the array of senders, which is now known to exist.
562 scheduleCleanup(sendersForReceiver.get(receiver)!);
563 }
564
565 // Schedule a cleanup of the receivers.
566 scheduleCleanup(receivers);
567 }
568
569 /**
570 * Remove all connections where the given object is the receiver.
571 *
572 * @param receiver - The receiver object of interest.
573 */
574 export function disconnectReceiver(receiver: unknown): void {
575 // If there are no senders, there is nothing to do.
576 let senders = sendersForReceiver.get(receiver);
577 if (!senders || senders.length === 0) {
578 return;
579 }
580
581 // Clear each sender connection.
582 for (const connection of senders) {
583 // Skip connections which have already been cleared.
584 if (!connection.signal) {
585 continue;
586 }
587
588 // Lookup the sender for the connection.
589 let sender = connection.signal.sender;
590
591 // Clear the connection.
592 connection.signal = null;
593
594 // Cleanup the array of receivers, which is now known to exist.
595 scheduleCleanup(receiversForSender.get(sender)!);
596 }
597
598 // Schedule a cleanup of the list of senders.
599 scheduleCleanup(senders);
600 }
601
602 /**
603 * Remove all connections where an object is the sender or receiver.
604 *
605 * @param object - The object of interest.
606 */
607 export function disconnectAll(object: unknown): void {
608 // Remove all connections where the given object is the sender.
609 disconnectSender(object);
610 // Remove all connections where the given object is the receiver.
611 disconnectReceiver(object);
612 }
613
614 /**
615 * Emit a signal and invoke its connected slots.
616 *
617 * @param signal - The signal of interest.
618 *
619 * @param args - The args to pass to the connected slots.
620 *
621 * #### Notes
622 * Slots are invoked synchronously in connection order.
623 *
624 * Exceptions thrown by connected slots will be caught and logged.
625 */
626 export function emit<T, U>(signal: Signal<T, U>, args: U): void {
627 // If there are no receivers, there is nothing to do.
628 let receivers = receiversForSender.get(signal.sender);
629 if (!receivers || receivers.length === 0) {
630 return;
631 }
632
633 // Invoke the slots for connections with a matching signal.
634 // Any connections added during emission are not invoked.
635 for (let i = 0, n = receivers.length; i < n; ++i) {
636 let connection = receivers[i];
637 if (connection.signal === signal) {
638 invokeSlot(connection, args);
639 }
640 }
641 }
642
643 /**
644 * An object which holds connection data.
645 */
646 interface IConnection {
647 /**
648 * The signal for the connection.
649 *
650 * A `null` signal indicates a cleared connection.
651 */
652 signal: Signal<any, any> | null;
653
654 /**
655 * The slot connected to the signal.
656 */
657 readonly slot: Slot<any, any>;
658
659 /**
660 * The `this` context for the slot.
661 */
662 readonly thisArg: any;
663 }
664
665 /**
666 * A weak mapping of sender to array of receiver connections.
667 */
668 const receiversForSender = new WeakMap<any, IConnection[]>();
669
670 /**
671 * A weak mapping of receiver to array of sender connections.
672 */
673 const sendersForReceiver = new WeakMap<any, IConnection[]>();
674
675 /**
676 * A set of connection arrays which are pending cleanup.
677 */
678 const dirtySet = new Set<IConnection[]>();
679
680 /**
681 * A function to schedule an event loop callback.
682 */
683 const schedule = (() => {
684 let ok = typeof requestAnimationFrame === 'function';
685 return ok ? requestAnimationFrame : setImmediate;
686 })();
687
688 /**
689 * Find a connection which matches the given parameters.
690 */
691 function findConnection(
692 connections: IConnection[],
693 signal: Signal<any, any>,
694 slot: Slot<any, any>,
695 thisArg: any
696 ): IConnection | undefined {
697 return find(
698 connections,
699 connection =>
700 connection.signal === signal &&
701 connection.slot === slot &&
702 connection.thisArg === thisArg
703 );
704 }
705
706 /**
707 * Invoke a slot with the given parameters.
708 *
709 * The connection is assumed to be valid.
710 *
711 * Exceptions in the slot will be caught and logged.
712 */
713 function invokeSlot(connection: IConnection, args: any): void {
714 let { signal, slot, thisArg } = connection;
715 try {
716 slot.call(thisArg, signal!.sender, args);
717 } catch (err) {
718 exceptionHandler(err);
719 }
720 }
721
722 /**
723 * Schedule a cleanup of a connection array.
724 *
725 * This will add the array to the dirty set and schedule a deferred
726 * cleanup of the array contents. On cleanup, any connection with a
727 * `null` signal will be removed from the array.
728 */
729 function scheduleCleanup(array: IConnection[]): void {
730 if (dirtySet.size === 0) {
731 schedule(cleanupDirtySet);
732 }
733 dirtySet.add(array);
734 }
735
736 /**
737 * Cleanup the connection lists in the dirty set.
738 *
739 * This function should only be invoked asynchronously, when the
740 * stack frame is guaranteed to not be on the path of user code.
741 */
742 function cleanupDirtySet(): void {
743 dirtySet.forEach(cleanupConnections);
744 dirtySet.clear();
745 }
746
747 /**
748 * Cleanup the dirty connections in a connections array.
749 *
750 * This will remove any connection with a `null` signal.
751 *
752 * This function should only be invoked asynchronously, when the
753 * stack frame is guaranteed to not be on the path of user code.
754 */
755 function cleanupConnections(connections: IConnection[]): void {
756 ArrayExt.removeAllWhere(connections, isDeadConnection);
757 }
758
759 /**
760 * Test whether a connection is dead.
761 *
762 * A dead connection has a `null` signal.
763 */
764 function isDeadConnection(connection: IConnection): boolean {
765 return connection.signal === null;
766 }
767 }