Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor fake PeerJS class.
3 *
4 * For convenient debugging. Create two FakePeers in one browser window. Then a single
5 * debugger can see all the communication within its call stack.
6 *
7 * @copyright See AUTHORS.txt
8 */
9
10 ve.FakePeer = function veFakePeer() {
11 this.id = 'p' + this.constructor.static.peers.length;
12 this.constructor.static.peers.push( this );
13 this.connections = [];
14 this.handlers = new Map();
15 Promise.resolve( this.id ).then( this.callHandlers.bind( this, 'open' ) );
16 };
17
18 /* Initialization */
19
20 OO.initClass( ve.FakePeer );
21
22 /* Static properties */
23
24 ve.FakePeer.static.peers = [];
25
26 /* Methods */
27
28 ve.FakePeer.prototype.on = function ( ev, f ) {
29 let handlers = this.handlers.get( ev );
30 if ( !handlers ) {
31 handlers = [];
32 this.handlers.set( ev, handlers );
33 }
34 handlers.push( f );
35 };
36
37 ve.FakePeer.prototype.callHandlers = function ( type, ...args ) {
38 ( this.handlers.get( type ) || [] ).forEach( ( handler ) => {
39 handler( ...args );
40 } );
41 };
42
43 ve.FakePeer.prototype.connect = function ( id ) {
44 const peer = this.constructor.static.peers.find( ( peerI ) => peerI.id === id );
45 if ( !peer ) {
46 throw new Error( 'Unknown id: ' + id );
47 }
48 const thisConn = new ve.FakePeerConnection( peer.id + '-' + this.id, peer );
49 const peerConn = new ve.FakePeerConnection( this.id + '-' + peer.id, this );
50 thisConn.other = peerConn;
51 peerConn.other = thisConn;
52 this.connections.push( thisConn );
53 peer.connections.push( peerConn );
54 Promise.resolve( peerConn ).then( peer.callHandlers.bind( peer, 'connection' ) );
55 Promise.resolve( thisConn.id ).then( thisConn.callHandlers.bind( thisConn, 'open' ) );
56 Promise.resolve( peerConn.id ).then( peerConn.callHandlers.bind( peerConn, 'open' ) );
57 return thisConn;
58 };
59
60 ve.FakePeerConnection = function VeFakePeerConnection( id, peer ) {
61 this.id = id;
62 this.peer = peer;
63 this.other = null;
64 this.handlers = new Map();
65 };
66
67 OO.initClass( ve.FakePeerConnection );
68
69 ve.FakePeerConnection.prototype.on = function ( ev, f ) {
70 let handlers = this.handlers.get( ev );
71 if ( !handlers ) {
72 handlers = [];
73 this.handlers.set( ev, handlers );
74 }
75 handlers.push( f );
76 };
77
78 ve.FakePeerConnection.prototype.callHandlers = function ( type, ...args ) {
79 ( this.handlers.get( type ) || [] ).forEach( ( handler ) => {
80 handler( ...args );
81 } );
82 };
83
84 ve.FakePeerConnection.prototype.setOther = function ( other ) {
85 this.other = other;
86 Promise.resolve( this.id ).then( this.callHandlers.bind( this, 'open' ) );
87 };
88
89 ve.FakePeerConnection.prototype.send = function ( data ) {
90 Promise.resolve( data ).then( this.other.callHandlers.bind( this.other, 'data' ) );
91 };