1
1
import type {
2
+ RealtimeListener ,
2
3
ReceivedStatusUpdate ,
3
4
SendingStatusUpdate ,
4
5
Webxdc ,
@@ -23,20 +24,28 @@ type Connect = (
23
24
export type WebXdcMulti = {
24
25
connect : Connect ;
25
26
sendUpdate : Webxdc < any > [ "sendUpdate" ] ;
27
+ joinRealtimeChannel : Webxdc < any > [ "joinRealtimeChannel" ]
26
28
} ;
27
29
28
30
export type UpdateDescr = [ ReceivedStatusUpdate < any > , string ] ;
29
31
30
32
export type OnMessage = ( message : Message ) => void ;
31
33
34
+ export type OnRealtime = ( message : Message ) => void ;
35
+
32
36
export interface IProcessor {
33
37
createClient ( id : string ) : WebXdcMulti ;
34
38
clear ( ) : void ;
35
39
removeClient ( id : string ) : void ;
36
40
}
37
41
42
+ class Realtime {
43
+ constructor ( public listener : ( data : Uint8Array ) => void = ( ) => { } ) { } ;
44
+ }
45
+
38
46
class Client implements WebXdcMulti {
39
47
updateListener : UpdateListenerMulti | null = null ;
48
+ realtime : Realtime | null = null ;
40
49
clearListener : ClearListener | null = null ;
41
50
updateSerial : number | null = null ;
42
51
deleteListener : DeleteListener | null = null ;
@@ -50,6 +59,10 @@ class Client implements WebXdcMulti {
50
59
this . processor . distribute ( this . id , update , descr ) ;
51
60
}
52
61
62
+ sendRealtimeData ( data : Uint8Array ) : void {
63
+ this . processor . distributeRealtime ( this . id , data ) ;
64
+ }
65
+
53
66
connect (
54
67
listener : UpdateListenerMulti ,
55
68
serial : number ,
@@ -112,7 +125,29 @@ class Client implements WebXdcMulti {
112
125
}
113
126
this . updateListener ( [ [ update , descr ] ] ) ;
114
127
}
128
+
129
+ receiveRealtime ( data : Uint8Array ) {
130
+ if ( this . updateListener == null || this . updateSerial == null ) {
131
+ return ;
132
+ }
133
+ if ( this . realtime && this . realtime . listener )
134
+ this . realtime ?. listener ( data )
135
+ }
115
136
137
+ joinRealtimeChannel ( ) : RealtimeListener {
138
+ return {
139
+ setListener : ( listener ) => {
140
+ this . realtime = new Realtime ( listener )
141
+ } ,
142
+ leave : ( ) => {
143
+ this . realtime = null
144
+ } ,
145
+ send : ( data ) => {
146
+ this . sendRealtimeData ( data )
147
+ }
148
+ }
149
+ }
150
+
116
151
clear ( ) {
117
152
if (
118
153
this . clearListener == null ||
@@ -153,6 +188,23 @@ class Processor implements IProcessor {
153
188
this . clients . splice ( client_index , 1 ) ;
154
189
}
155
190
191
+ distributeRealtime (
192
+ instanceId : string ,
193
+ data : Uint8Array ,
194
+ ) {
195
+ this . onMessage ( {
196
+ type : "realtime-sent" ,
197
+ instanceId : instanceId ,
198
+ instanceColor : getColorForId ( instanceId ) ,
199
+ data,
200
+ timestamp : Date . now ( ) ,
201
+ } ) ;
202
+ for ( const client of this . clients ) {
203
+ client . receiveRealtime ( data ) ;
204
+ }
205
+ }
206
+
207
+
156
208
distribute (
157
209
instanceId : string ,
158
210
update : SendingStatusUpdate < any > ,
0 commit comments