-
Notifications
You must be signed in to change notification settings - Fork 0
/
Room.js
97 lines (81 loc) · 2.68 KB
/
Room.js
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
import SyncedList from './SyncedList.js';
import SyncedMap from './SyncedMap.js';
import * as Y from 'yjs';
/**
* @classdesc Room object returned when calling <tt>Client.enter</tt>.
* @hideconstructor
*/
class Room {
#wsProvider;
#ydoc;
#roomId;
constructor(wsProvider, ydoc, roomId) {
this.#wsProvider = wsProvider;
this.#ydoc = ydoc;
this.#roomId = roomId;
}
/** Subscribes to updates for an item.
* If the <tt>subscribedItem</tt> is a SyncedList or SyncedMap, the provided callback is executed whenever that shared type changes.
* If the <tt>subscribedItem</tt> is <tt>'others'</tt>, the provided callback is executed whenever another client's presence changes.
*
* @param {SyncedList | SyncedMap | string} subscribedItem
* @param {function} callback
*/
subscribe(subscribedItem, callback) {
if (subscribedItem instanceof SyncedList || subscribedItem instanceof SyncedMap) {
subscribedItem.observe(callback);
} else if (subscribedItem === 'others') {
this.#wsProvider.awareness.on('change', callback);
}
}
/** Stops subscribing to the SyncedList or SyncedMap passed as an argument.*/
unsubscribe(subscribedItem, callback) {
if (subscribedItem instanceof SyncedList || subscribedItem instanceof SyncedMap) {
subscribedItem.unobserve(callback);
}
}
/** Returns the Room id.*/
getRoomId() {
return this.#roomId;
}
// Gets the presence of the current user.
// getPresence() {
// }
/** Returns the id of the client.*/
getClientId() {
return this.#wsProvider.awareness.clientID;
}
/** Updates the presence of the client. Properties passed as arguments will be updated, while other properties of presence will remain unchanged.*/
updatePresence(updatedPresence) {
const currentPresence = this.#wsProvider.awareness.getLocalState();
this.#wsProvider.awareness.setLocalState({
...currentPresence,
...updatedPresence,
});
}
/** Returns all other users in the Room.*/
getOthers() {
return this.#wsProvider.awareness.getStates();
}
/** Merges operations in the callback function into a single operation.*/
bundle(callback) {
this.#ydoc.transact(callback);
}
/** Returns a new top-level SyncedList.*/
newList(name) {
return new SyncedList(this.#ydoc, name);
}
/** Returns a new top-level SyncedMap.*/
newMap(name) {
return new SyncedMap(this.#ydoc, name);
}
/** Returns a new SyncedList that can be nested within another synced type.*/
newNestedList() {
return new Y.Array();
}
/** Returns a new SyncedMap that can be nested within another synced type.*/
newNestedMap() {
return new Y.Map();
}
}
export default Room;