Skip to content

Instantly share code, notes, and snippets.

@josephg
Last active May 6, 2021 05:19
Show Gist options
  • Save josephg/88c006724435a61afaec5ff3f1bacd87 to your computer and use it in GitHub Desktop.
Save josephg/88c006724435a61afaec5ff3f1bacd87 to your computer and use it in GitHub Desktop.
import * as Y from 'yjs'
const makeYDoc = (clientId: number) => {
const doc = new Y.Doc()
doc.clientID = clientId
return doc
}
const yjsMergeInto = (target: Y.Doc, src: Y.Doc) => {
const sv = Y.encodeStateVector(target)
const update = Y.encodeStateAsUpdateV2(src, sv)
Y.applyUpdateV2(target, update)
}
const a = makeYDoc(1)
a.getArray().insert(0, ['a']) // doca is ['a']
const b = makeYDoc(3)
b.getArray().insert(0, ['b']) // docb is ['b']
const c = makeYDoc(0)
yjsMergeInto(c, a)
yjsMergeInto(c, b)
c.getArray().insert(1, ['c'])
// docc inserts 'c' between 'a' and 'b' -> ['a', 'c', 'b']
a.getArray().insert(1, ['a1']) // a is ['a', 'a1']
b.getArray().insert(0, ['b0']) // b is ['b0', 'b']
/// If we merge everything together...
yjsMergeInto(a, b)
yjsMergeInto(a, c)
console.log(a.getArray().toArray()) // What should the order be?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment