Line data Source code
1 : import * as Y from 'yjs'
2 :
3 1 : const REMOTE_DOC_UPDATE_ORIGIN = Symbol('remote-doc-update')
4 :
5 1 : export class FollowerDoc extends EventTarget {
6 : readonly doc = new Y.Doc()
7 : updatesApplied = 0
8 :
9 : /**
10 : * `Y.applyUpdate` integrates structs as it decodes them, so a malformed
11 : * frame would leave the doc holding its readable prefix. Decoding the whole
12 : * frame first makes the apply all-or-nothing.
13 : */
14 : applyRemoteUpdate(update: Uint8Array): void {
15 0 : Y.decodeUpdate(update)
16 0 : Y.applyUpdate(this.doc, update, REMOTE_DOC_UPDATE_ORIGIN)
17 0 : this.updatesApplied++
18 0 : this.dispatchEvent(
19 : new CustomEvent('update', {
20 : detail: { update, updatesApplied: this.updatesApplied }
21 : })
22 : )
23 : }
24 :
25 : stateVector(): Uint8Array {
26 0 : return Y.encodeStateVector(this.doc)
27 : }
28 :
29 : destroy(): void {
30 0 : this.doc.destroy()
31 : }
32 : }
|