11import Listenable from '@/lib/Listenable' ;
22
3+ /**
4+ * A fake WebSocket that mimics the WebSocket interface but does nothing.
5+ * Used when there's no active user session to prevent console errors.
6+ */
7+ class FakeWebSocket {
8+ constructor ( ) {
9+ this . readyState = WebSocket . OPEN ;
10+ }
11+
12+ // eslint-disable-next-line class-methods-use-this
13+ close ( ) {
14+ // Do nothing
15+ }
16+
17+ // eslint-disable-next-line class-methods-use-this
18+ send ( ) {
19+ // Do nothing
20+ }
21+ }
22+
323export default class Socket extends Listenable {
424 constructor ( websocketCreator ) {
525 super ( ) ;
626 this . websocketCreator = websocketCreator ;
27+ this . sessionActive = false ;
28+ this . wantStart = false ;
729 }
830
9- start ( ) {
31+ /**
32+ * Sets whether the user session is active.
33+ * If session becomes active and start() was previously called, creates real WebSocket.
34+ * If session becomes inactive, stops real WebSocket and switches to fake one.
35+ * @param {boolean } isActive - Whether the user session is active
36+ */
37+ setSessionActive ( isActive ) {
38+ const wasActive = this . sessionActive ;
39+ this . sessionActive = isActive ;
40+
41+ if ( isActive && ! wasActive && this . wantStart ) {
42+ // Session became active and we wanted to start - create real socket
43+ this . startRealSocket ( ) ;
44+ } else if ( ! isActive && wasActive && this . ws ) {
45+ // Session became inactive - stop real socket
46+ this . stop ( ) ;
47+ }
48+ }
49+
50+ /**
51+ * Internal method to start a real WebSocket connection.
52+ * Only called when session is active.
53+ */
54+ startRealSocket ( ) {
1055 if ( this . ws != null ) {
11- throw new Error ( 'Websocket already started. Please stop it before starting.' ) ;
56+ return ;
1257 }
1358 this . ws = this . websocketCreator ( ) ;
1459 this . ws . onclose = ( ) => {
@@ -17,19 +62,38 @@ export default class Socket extends Listenable {
1762 }
1863 this . ws = null ;
1964 setTimeout ( ( ) => {
20- this . start ( ) ;
65+ if ( this . sessionActive ) {
66+ this . startRealSocket ( ) ;
67+ }
2168 } , 2000 ) ;
2269 } ;
2370 this . ws . onmessage = ( { data } ) => {
2471 this . callListeners ( JSON . parse ( data ) ) ;
2572 } ;
2673 }
2774
75+ start ( ) {
76+ this . wantStart = true ;
77+
78+ if ( this . ws != null ) {
79+ return ; // Already running (real or fake)
80+ }
81+
82+ if ( this . sessionActive ) {
83+ // Session is active, create real WebSocket
84+ this . startRealSocket ( ) ;
85+ } else {
86+ // No session, create fake WebSocket to avoid errors
87+ this . ws = new FakeWebSocket ( ) ;
88+ }
89+ }
90+
2891 isRunning ( ) {
2992 return this . ws != null ;
3093 }
3194
3295 stop ( ) {
96+ this . wantStart = false ;
3397 if ( ! this . ws ) {
3498 return ;
3599 }
0 commit comments