0
# Connection Management
1
2
Real-time synchronization and peer-to-peer communication management for maintaining consistent state across multiple clients.
3
4
## Capabilities
5
6
### Connector Interface
7
8
The connector handles all peer-to-peer communication and synchronization logic.
9
10
```javascript { .api }
11
/**
12
* Yjs Connector interface for managing peer connections
13
*/
14
interface YjsConnector {
15
/**
16
* Listen for user join/leave events
17
* @param {function} callback - Event handler for user events
18
*/
19
onUserEvent(callback: (event: UserEvent) => void): void;
20
21
/**
22
* Execute callback when synced with at least one user
23
* @param {function} callback - Function to execute when synced
24
*/
25
whenSynced(callback: () => void): void;
26
27
/**
28
* Force disconnect from all peers
29
*/
30
disconnect(): void;
31
32
/**
33
* Try to reconnect to peers
34
*/
35
reconnect(): void;
36
37
/**
38
* Boolean indicating sync status with other peers
39
*/
40
isSynced: boolean;
41
}
42
```
43
44
**Usage Examples:**
45
46
```javascript
47
// Monitor connection status
48
Y({
49
db: { name: 'memory' },
50
connector: {
51
name: 'websockets-client',
52
room: 'status-demo',
53
url: 'ws://localhost:1234'
54
},
55
share: { doc: 'Text' }
56
}).then(function (y) {
57
const connector = y.connector;
58
59
// Check initial sync status
60
console.log('Initially synced:', connector.isSynced);
61
62
// Wait for sync before allowing edits
63
connector.whenSynced(function() {
64
console.log('Ready for collaboration!');
65
enableEditing();
66
});
67
68
// Monitor user events
69
connector.onUserEvent(function(event) {
70
if (event.action === 'userJoined') {
71
console.log('User joined:', event.user);
72
showNotification(event.user + ' joined the session');
73
} else if (event.action === 'userLeft') {
74
console.log('User left:', event.user);
75
showNotification(event.user + ' left the session');
76
}
77
});
78
});
79
80
// Connection management with manual control
81
Y({
82
db: { name: 'indexeddb' },
83
connector: {
84
name: 'webrtc',
85
room: 'manual-control'
86
},
87
share: { canvas: 'Array' }
88
}).then(function (y) {
89
const connector = y.connector;
90
91
// Temporary disconnect for maintenance
92
function performMaintenance() {
93
connector.disconnect();
94
console.log('Disconnected for maintenance');
95
96
// Perform offline operations
97
performOfflineWork();
98
99
// Reconnect after maintenance
100
setTimeout(function() {
101
connector.reconnect();
102
console.log('Reconnected after maintenance');
103
}, 5000);
104
}
105
106
// Auto-reconnect on network issues
107
window.addEventListener('online', function() {
108
if (!connector.isSynced) {
109
connector.reconnect();
110
}
111
});
112
113
window.addEventListener('offline', function() {
114
console.log('Network offline - working in offline mode');
115
});
116
});
117
```
118
119
### User Event Handling
120
121
Track users joining and leaving collaborative sessions.
122
123
```javascript { .api }
124
/**
125
* Listen for user join/leave events
126
* @param {function} callback - Event handler receiving UserEvent objects
127
*/
128
onUserEvent(callback: (event: UserEvent) => void): void;
129
```
130
131
**Usage Examples:**
132
133
```javascript
134
// User presence system
135
Y({
136
db: { name: 'memory' },
137
connector: {
138
name: 'websockets-client',
139
room: 'presence-demo',
140
url: 'ws://localhost:1234'
141
},
142
share: {
143
doc: 'Text',
144
cursors: 'Map'
145
}
146
}).then(function (y) {
147
const userList = [];
148
149
y.connector.onUserEvent(function(event) {
150
if (event.action === 'userJoined') {
151
userList.push(event.user);
152
updateUsersList(userList);
153
154
// Initialize cursor tracking for new user
155
y.share.cursors.set(event.user, {
156
position: 0,
157
color: generateUserColor(event.user)
158
});
159
160
} else if (event.action === 'userLeft') {
161
const index = userList.indexOf(event.user);
162
if (index > -1) {
163
userList.splice(index, 1);
164
updateUsersList(userList);
165
166
// Remove cursor tracking
167
y.share.cursors.delete(event.user);
168
}
169
}
170
});
171
});
172
```
173
174
### Synchronization Management
175
176
Control when operations can be performed based on sync status.
177
178
```javascript { .api }
179
/**
180
* Execute callback when synced with at least one user
181
* @param {function} callback - Function to execute when synced
182
*/
183
whenSynced(callback: () => void): void;
184
```
185
186
**Usage Examples:**
187
188
```javascript
189
// Ensure sync before critical operations
190
Y({
191
db: { name: 'indexeddb' },
192
connector: {
193
name: 'webrtc',
194
room: 'critical-ops'
195
},
196
share: {
197
document: 'Text',
198
metadata: 'Map'
199
}
200
}).then(function (y) {
201
// Wait for sync before loading document
202
y.connector.whenSynced(function() {
203
// Safe to perform operations that depend on remote state
204
loadDocumentContent();
205
enableCollaborativeFeatures();
206
207
// Show sync indicator
208
showSyncStatus('Connected and synced');
209
});
210
211
// Monitor ongoing sync status
212
setInterval(function() {
213
if (y.connector.isSynced) {
214
showSyncStatus('Synced');
215
} else {
216
showSyncStatus('Syncing...');
217
}
218
}, 1000);
219
});
220
221
// Conflict resolution with sync awareness
222
Y({
223
db: { name: 'memory' },
224
connector: {
225
name: 'websockets-client',
226
room: 'conflict-demo',
227
url: 'ws://localhost:1234'
228
},
229
share: {
230
counter: 'Map'
231
}
232
}).then(function (y) {
233
function incrementCounter() {
234
y.connector.whenSynced(function() {
235
// Get current value after sync
236
const current = y.share.counter.get('value') || 0;
237
y.share.counter.set('value', current + 1);
238
});
239
}
240
241
// Safe counter increment button
242
document.getElementById('increment').onclick = incrementCounter;
243
});
244
```
245
246
### Connection Control
247
248
Manual control over connection state for advanced use cases.
249
250
```javascript { .api }
251
/**
252
* Force disconnect from all peers
253
* Local state is preserved
254
*/
255
disconnect(): void;
256
257
/**
258
* Try to reconnect to peers
259
* Syncs any changes made while disconnected
260
*/
261
reconnect(): void;
262
```
263
264
**Usage Examples:**
265
266
```javascript
267
// Bandwidth management
268
Y({
269
db: { name: 'indexeddb' },
270
connector: {
271
name: 'websockets-client',
272
room: 'bandwidth-mgmt',
273
url: 'ws://localhost:1234'
274
},
275
share: { doc: 'Text' }
276
}).then(function (y) {
277
let isLowBandwidth = false;
278
279
// Monitor connection quality
280
function checkConnectionQuality() {
281
// Disconnect during low bandwidth to prevent data loss
282
if (isLowBandwidth && y.connector.isSynced) {
283
console.log('Low bandwidth detected - working offline');
284
y.connector.disconnect();
285
showBandwidthWarning();
286
}
287
288
// Reconnect when bandwidth improves
289
if (!isLowBandwidth && !y.connector.isSynced) {
290
console.log('Bandwidth improved - reconnecting');
291
y.connector.reconnect();
292
hideBandwidthWarning();
293
}
294
}
295
296
// Simulate bandwidth monitoring
297
setInterval(checkConnectionQuality, 5000);
298
});
299
300
// Graceful shutdown
301
Y({
302
db: { name: 'memory' },
303
connector: {
304
name: 'webrtc',
305
room: 'graceful-shutdown'
306
},
307
share: { state: 'Map' }
308
}).then(function (y) {
309
// Save work before page unload
310
window.addEventListener('beforeunload', function(e) {
311
// Ensure final sync before disconnect
312
if (y.connector.isSynced) {
313
y.share.state.set('lastSaved', Date.now());
314
315
// Brief delay to allow sync
316
setTimeout(function() {
317
y.connector.disconnect();
318
}, 100);
319
}
320
});
321
});
322
```
323
324
## Event Types
325
326
### User Events
327
328
```javascript { .api }
329
interface UserEvent {
330
/** Action type */
331
action: 'userJoined' | 'userLeft';
332
/** User identifier */
333
user: string;
334
}
335
```
336
337
## Connection States
338
339
### Sync Status
340
341
The `isSynced` boolean property indicates whether the instance is currently synchronized with at least one other peer:
342
343
- `true` - Connected and synced with one or more peers
344
- `false` - Either disconnected or still synchronizing
345
346
### Connection Lifecycle
347
348
1. **Initial Connection** - Instance attempts to connect to other peers
349
2. **Synchronization** - Exchange of current state with connected peers
350
3. **Synced State** - Real-time updates flowing bidirectionally
351
4. **Disconnection** - Temporary or permanent loss of connection
352
5. **Reconnection** - Automatic or manual restoration of connection
353
6. **Re-synchronization** - Exchange of changes made while disconnected