/
eventsource.ts
375 lines (334 loc) · 10.4 KB
/
eventsource.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import {
NEW_LISTENER,
REMOVE_LISTENER,
ERROR,
CHANGE,
TIMEOUT,
ERROR_TIMEOUT,
} from "./constants"
import { Observable, Observer } from "./observable"
import { Flags } from "./flags"
import { stack } from "./trace/trace"
import { delay } from "./utils"
import { throwError } from "./error"
/**
* @category JDOM
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EventHandler = (...args: any[]) => void
interface Listener {
handler: EventHandler
once: boolean
stackTrace?: string
}
function normalizeEventNames(eventNames: string | string[]): string[] {
if (!eventNames) eventNames = []
if (typeof eventNames === "string") eventNames = [eventNames]
return eventNames
}
/**
* Base interface for evented nodes in Jacdac
* @category JDOM
*/
export interface IEventSource {
readonly nodeId: number
changeId: number
/**
* Subscribes to an event and returns the unsubscription handler
* @param eventName
* @param next
*/
subscribe<T>(
eventName: string | string[],
next: (value: T) => void,
): () => void
}
/**
* Given a node or set of nodes, generate a stable string that can be used to track dependencies in frameworks like React.
* @param nodes
* @returns
* @category JDOM
*/
export function dependencyId(nodes: IEventSource | IEventSource[]) {
if (Array.isArray(nodes))
return nodes?.map(node => node?.nodeId || "?").join(",") || ""
else return nodes?.nodeId || ""
}
let nextNodeId = 0
/**
* Collects unsubscribe handlers and unmounts them
*/
export class JDCancellationToken {
private subscriptions: (() => void)[] = []
constructor() {}
mount(...items: (() => void)[]) {
this.subscriptions.push(...items)
}
unmount() {
const us = this.subscriptions
this.subscriptions = []
us.forEach(unsub => unsub())
}
}
/**
* Base class for evented nodes in Jacdac
* @category JDOM
*/
export class JDEventSource implements IEventSource {
/**
* Gets an internal unique node identifier, mostly used for debugging.
* @category JDOM
*/
public readonly nodeId = nextNodeId++
private readonly listeners: Record<string, Listener[]> = {}
/**
* Gets a counter of event emit calls.
* @category JDOM
*/
readonly eventStats: Record<string, number> = {}
/**
* Gets a counter map from events to new listener counts
* @category JDOM
*/
newListenerStats: Record<string, number> = undefined
/**
* @internal
*/
constructor() {}
/**
* Registers a handler for one or more events
* @param eventName name or names of the events to subscribe
* @param handler handler to register
* @returns current object instance
* @category JDOM
*/
on(eventName: string | string[], handler: EventHandler) {
if (!handler) return this
normalizeEventNames(eventName).forEach(eventName =>
this.addListenerInternal(eventName, handler, false),
)
return this
}
/**
* Unregisters a handler for one or more events
* @param eventName name or names of the events to subscribe
* @param handler handler to unregister
* @returns current object instance
* @category JDOM
*/
off(eventName: string | string[], handler: EventHandler) {
normalizeEventNames(eventName).forEach(eventName =>
this.removeListenerInternal(eventName, handler),
)
return this
}
/**
* Registers a handler for one or more events to run only once.
* @param eventName name or names of the events to subscribe
* @param handler handler to execute
* @returns current object instance
* @category JDOM
*/
once(eventName: string | string[], handler: EventHandler) {
normalizeEventNames(eventName).forEach(eventName =>
this.addListenerInternal(eventName, handler, true),
)
return this
}
/**
* Awaits an event with a timeout. Throws JacdacError with timeout if operation does not return.
* @param eventName
* @param timeout
*/
async awaitOnce(
eventName: string | string[],
token?: JDCancellationToken,
): Promise<void> {
if (!eventName) return
const p = new Promise<void>(resolve => {
const handler = () => resolve?.()
this.once(eventName, handler)
token?.mount(() => this.off(eventName, handler))
})
return p
}
private addListenerInternal(
eventName: string,
handler: EventHandler,
once: boolean,
): void {
if (!eventName || !handler) {
return
}
const eventListeners =
this.listeners[eventName] || (this.listeners[eventName] = [])
const listener = eventListeners.find(
listener => listener.handler === handler,
)
if (listener) {
listener.once = !!once
return
}
eventListeners.push({
handler,
once: !!once,
// debug only collection of trace for leak detection
stackTrace: Flags.diagnostics && stack(),
})
this.emit(NEW_LISTENER, eventName, handler)
// diagnostics
if (Flags.diagnostics) {
if (!this.newListenerStats) this.newListenerStats = {}
this.newListenerStats[eventName] =
(this.newListenerStats[eventName] || 0) + 1
}
}
private removeListenerInternal(
eventName: string,
handler: EventHandler,
): void {
if (!eventName || !handler) return
const eventListeners = this.listeners[eventName]
if (eventListeners) {
for (let i = 0; i < eventListeners.length; ++i) {
const listener = eventListeners[i]
if (handler === listener.handler) {
eventListeners.splice(i, 1)
this.emit(REMOVE_LISTENER, eventName, handler)
return
}
}
}
}
/**
* Synchronously calls each of the listeners registered for the event named eventName,
* in the order they were registered, passing the supplied arguments to each.
* @param eventName
* @param args
* @category JDOM
*/
emit(eventName: string, ...args: unknown[]): boolean {
if (!eventName) return false
// track event stats
this.eventStats[eventName] = (this.eventStats[eventName] || 0) + 1
const eventListeners = this.listeners[eventName]
if (!eventListeners || eventListeners.length == 0) {
// report unhandled errors
if (eventName == ERROR && Flags.diagnostics) console.debug(args[0])
return false
}
for (let i = 0; i < eventListeners.length; ++i) {
const listener = eventListeners[i]
const handler = listener.handler
if (listener.once) {
eventListeners.splice(i, 1)
--i
}
try {
// eslint-disable-next-line prefer-spread
handler.apply(null, args)
} catch (e) {
// avoid recursive errors in error handler
if (eventName !== ERROR) this.emit(ERROR, e)
}
}
return true
}
/**
* Gets the number of listeners for a given event
* @param eventName name of the event
* @returns number of registered handlers
* @category JDOM
*/
listenerCount(eventName: string): number {
if (!eventName) return 0
const listeners = this.listeners[eventName]
return listeners?.length || 0
}
/**
* Gets the list stack trace where an event was registered. Only enabled if ``Flags.debug`` is true.
* @param eventName name of the event
* @returns stack traces where a listener was added
* @category JDOM
*/
listenerStackTraces(eventName: string): string[] {
const listeners = this.listeners[eventName]
return listeners?.map(listener => listener.stackTrace)
}
/**
* Returns an array listing the events for which the emitter has registered listeners.
* @category JDOM
*/
eventNames(): string[] {
return Object.keys(this.listeners)
}
/**
* Creates an observable from the given event
* @param eventName
* @category JDOM
*/
observe<T>(eventName: string | string[]): Observable<T> {
return new EventObservable<T>(this, normalizeEventNames(eventName))
}
/**
* Subscribes to an event and returns the unsubscription handler
* @param eventName
* @param next
* @category JDOM
*/
subscribe<T>(
eventName: string | string[],
next: (value: T) => void,
): () => void {
const observer = this.observe<T>(eventName)
return observer.subscribe({ next }).unsubscribe
}
/**
* Gets a counter for the ``CHANGE`` event.
* @category JDOM
*/
get changeId() {
return this.eventStats[CHANGE] || 0
}
}
export class JDSubscriptionScope {
private unsubscribers: (() => void)[] = []
private _unmounted = false
get unmounted() {
return this._unmounted
}
mount(unsubscribe: () => void): () => void {
this._unmounted = false
if (unsubscribe && this.unsubscribers.indexOf(unsubscribe) < 0)
this.unsubscribers.push(unsubscribe)
return unsubscribe
}
unmount() {
const us = this.unsubscribers
this.unsubscribers = []
us.forEach(u => u())
this._unmounted = true
}
}
class EventObservable<T> implements Observable<T> {
constructor(
public readonly eventEmitter: JDEventSource,
public readonly eventNames: string[],
) {
//console.log(`obs`, this.eventNames)
}
subscribe(observer: Observer<T>) {
//console.log(`on`, this.eventNames, observer)
if (observer.next) this.eventEmitter.on(this.eventNames, observer.next)
if (observer.error) this.eventEmitter.on(ERROR, observer.error)
// never completes
return {
unsubscribe: () => {
//console.log(`off`, this.eventNames, observer)
if (observer.next)
this.eventEmitter.off(this.eventNames, observer.next)
if (observer.error) this.eventEmitter.off(ERROR, observer.error)
},
}
}
}