This repository has been archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
demo.js
59 lines (55 loc) · 1.83 KB
/
demo.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
const { EditorState } = require("prosemirror-state");
const { EditorView } = require("prosemirror-view");
const { Node } = require("prosemirror-model");
const { schema } = require("prosemirror-schema-basic");
const Automerge = require("automerge");
const {
createAutomergeDoc,
applyTransaction,
toProsemirror,
AutomergePlugin,
createTransaction,
key
} = require("./src");
// create an origin state and serialize it to string
const originalDoc = schema.nodes.doc.create({}, [
schema.nodes.paragraph.create({}, [schema.text("hello world")])
]);
const startingAutomergeDoc = Automerge.change(
Automerge.init(),
createAutomergeDoc(originalDoc)
);
const startingDocString = Automerge.save(startingAutomergeDoc);
// create an editor which:
// - sends the current automerge document to the "remote" Automerge, when a ProseMirror change happens
// - creates/dispatches a ProseMirror transaction when a "remote" Automerge detects a change
function createEditor(automergeDocString, selector, merger) {
const actorId = Automerge.init()._actorId;
const doc = Automerge.load(automergeDocString, actorId);
const onDocChange = newDoc => {
merger.merge(newDoc);
};
const view = new EditorView(document.querySelector(selector), {
state: EditorState.create({
plugins: [new AutomergePlugin(doc, onDocChange)],
schema,
doc: toProsemirror(schema, doc)
})
});
merger.listeners.push(remoteDoc => {
view.dispatch(
createTransaction(view.state, key.getState(view.state), remoteDoc)
);
});
}
// extremely basic syncing between two Automerge documents
const mergeManager = {
doc: startingAutomergeDoc,
merge(newDoc) {
this.doc = Automerge.merge(this.doc, newDoc);
this.listeners.forEach(l => l(this.doc));
},
listeners: []
};
createEditor(startingDocString, "#editor-1", mergeManager);
createEditor(startingDocString, "#editor-2", mergeManager);