-
-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathDocument.ts
More file actions
259 lines (206 loc) · 5.72 KB
/
Document.ts
File metadata and controls
259 lines (206 loc) · 5.72 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { Mutex } from "async-mutex";
import {
Awareness,
applyAwarenessUpdate,
removeAwarenessStates,
} from "y-protocols/awareness";
import { Doc, applyUpdate, encodeStateAsUpdate } from "yjs";
import type Connection from "./Connection.ts";
import { OutgoingMessage } from "./OutgoingMessage.ts";
import type { AwarenessUpdate } from "./types.ts";
export class Document extends Doc {
awareness: Awareness;
callbacks = {
// eslint-disable-next-line @typescript-eslint/no-empty-function
onUpdate: (document: Document, origin: unknown, update: Uint8Array) => {},
beforeBroadcastStateless: (document: Document, stateless: string) => {},
};
connections: Map<
Connection,
{
clients: Set<any>;
}
> = new Map();
// The number of direct (non-websocket) connections to this document
directConnectionsCount = 0;
name: string;
isLoading: boolean;
isDestroyed = false;
saveMutex = new Mutex();
lastChangeTime = 0;
/**
* Constructor.
*/
constructor(name: string, yDocOptions?: object) {
super(yDocOptions);
this.name = name;
this.awareness = new Awareness(this);
this.awareness.setLocalState(null);
this.awareness.on("update", this.handleAwarenessUpdate.bind(this));
this.on("update", this.handleUpdate.bind(this));
this.isLoading = true;
}
/**
* Check if the Document (XMLFragment or Map) is empty
*/
isEmpty(fieldName: string): boolean {
return !this.get(fieldName)._start && !this.get(fieldName)._map.size;
}
/**
* Merge the given document(s) into this one
*/
merge(documents: Doc | Array<Doc>): Document {
(Array.isArray(documents) ? documents : [documents]).forEach((document) => {
applyUpdate(this, encodeStateAsUpdate(document));
});
return this;
}
/**
* Set a callback that will be triggered when the document is updated
*/
onUpdate(
callback: (document: Document, origin: unknown, update: Uint8Array) => void,
): Document {
this.callbacks.onUpdate = callback;
return this;
}
/**
* Set a callback that will be triggered before a stateless message is broadcasted
*/
beforeBroadcastStateless(
callback: (document: Document, stateless: string) => void,
): Document {
this.callbacks.beforeBroadcastStateless = callback;
return this;
}
/**
* Register a connection and a set of clients on this document keyed by the
* underlying websocket connection
*/
addConnection(connection: Connection): Document {
this.connections.set(connection, {
clients: new Set(),
});
return this;
}
/**
* Is the given connection registered on this document
*/
hasConnection(connection: Connection): boolean {
return this.connections.has(connection);
}
/**
* Remove the given connection from this document
*/
removeConnection(connection: Connection): Document {
const entry = this.connections.get(connection);
if (entry) {
removeAwarenessStates(
this.awareness,
Array.from(entry.clients),
null,
);
}
this.connections.delete(connection);
return this;
}
addDirectConnection(): Document {
this.directConnectionsCount += 1;
return this;
}
removeDirectConnection(): Document {
if (this.directConnectionsCount > 0) {
this.directConnectionsCount -= 1;
}
return this;
}
/**
* Get the number of active connections for this document
*/
getConnectionsCount(): number {
return this.connections.size + this.directConnectionsCount;
}
/**
* Get an array of registered connections
*/
getConnections(): Array<Connection> {
return Array.from(this.connections.keys());
}
/**
* Get the client ids for the given connection instance
*/
getClients(connection: Connection): Set<any> {
const entry = this.connections.get(connection);
return entry?.clients === undefined ? new Set() : entry.clients;
}
/**
* Has the document awareness states
*/
hasAwarenessStates(): boolean {
return this.awareness.getStates().size > 0;
}
/**
* Apply the given awareness update
*/
applyAwarenessUpdate(connection: Connection, update: Uint8Array): Document {
applyAwarenessUpdate(this.awareness, update, connection);
return this;
}
/**
* Handle an awareness update and sync changes to clients
* @private
*/
private handleAwarenessUpdate(
{ added, updated, removed }: AwarenessUpdate,
originConnection: Connection | null,
): Document {
const changedClients = added.concat(updated, removed);
if (originConnection !== null) {
const entry = this.connections.get(originConnection);
if (entry) {
added.forEach((clientId: any) => entry.clients.add(clientId));
removed.forEach((clientId: any) => entry.clients.delete(clientId));
}
}
for (const connection of this.getConnections()) {
const awarenessMessage = new OutgoingMessage(
connection.messageAddress,
).createAwarenessUpdateMessage(this.awareness, changedClients);
connection.send(awarenessMessage.toUint8Array());
}
return this;
}
/**
* Handle an updated document and sync changes to clients
*/
private handleUpdate(update: Uint8Array, origin: unknown): Document {
this.callbacks.onUpdate(this, origin, update);
for (const connection of this.getConnections()) {
const message = new OutgoingMessage(connection.messageAddress)
.createSyncMessage()
.writeUpdate(update);
connection.send(message.toUint8Array());
}
return this;
}
/**
* Broadcast stateless message to all connections
*/
public broadcastStateless(
payload: string,
filter?: (conn: Connection) => boolean,
): void {
this.callbacks.beforeBroadcastStateless(this, payload);
const connections = filter
? this.getConnections().filter(filter)
: this.getConnections();
connections.forEach((connection) => {
connection.sendStateless(payload);
});
}
destroy() {
super.destroy();
this.isDestroyed = true;
}
}
export default Document;