-
Notifications
You must be signed in to change notification settings - Fork 2
/
sharedb-codemirror.js
230 lines (210 loc) · 6.75 KB
/
sharedb-codemirror.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
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
class ShareDBCodeMirror {
/**
* @constructor
* @param {CodeMirror} codeMirror - a CodeMirror editor instance
* @param {Object} options - configuration options:
* - key: string; required. The key in the ShareDB doc at which to store the
* CodeMirror value. Deeply nested paths are currently not supported.
* - errorHandler: optional. A handler to which a single error message is
* provided. The default behavior is to print error messages to the console.
* - verbose: optional. If true, log messages will be printed to the console.
* @return {ShareDBCodeMirror} the created ShareDBCodeMirror object
*/
constructor(codeMirror, options) {
this.codeMirror = codeMirror;
this.key = options.key;
this.errorHandler = options.errorHandler || function (error) {
console.error(error);
};
var verbose = Boolean(options.verbose);
this.log = (...args) => {
if (verbose) {
console.debug.apply(console, args);
}
};
this.suppressChange = false;
this.codeMirrorBeforeChange = (...args) => { this.beforeLocalChange(...args); };
this.codeMirrorChanges = (...args) => { this.afterLocalChanges(...args); };
this.shareDBOp = (...args) => { this.onRemoteChange(...args); };
this.shareDBDel = (...args) => { this.onDocDelete(...args); };
this.shareDBError = (...args) => { this.onDocError(...args); };
}
/**
* Attaches a ShareDB document to the CodeMirror instance.
*
* @param {sharedb.Doc} doc
* @param {function (Object)=} callback - optional. Will be called when everything
* is hooked up. The first argument will be the error that occurred, if any.
*/
attachDoc(doc, callback) {
this.detachDoc();
doc.subscribe((error) => {
if (error) {
if (!callback) {
console.error(error);
}
} else {
this.doc = doc;
this.log('ShareDBCodeMirror: subscribed to doc', doc);
this.start();
}
if (callback) {
callback(error);
}
});
}
/**
* Starts listening for changes from the CodeMirror instance and the ShareDB
* document. For CodeMirror, it is necessary to register for both
* `beforeChange` and `changes` events: the first one is the only one to
* report the positions in the pre-change coordinate system, while the latter
* marks the end of the batch of operations.
*/
start() {
var doc = this.doc;
var codeMirror = this.codeMirror;
if (!doc.type) {
this.log('ShareDBCodeMirror: creating emtpy doc');
var data = {}
data[this.key] = '';
doc.create(data, (error) => {
if (error) {
this.errorHandler(error);
}
});
}
if (!doc.cm || doc.cm.version !== doc.version) {
var cmDoc = new codeMirror.constructor.Doc(doc.data[this.key]);
doc.cm = {doc: cmDoc}
}
codeMirror.swapDoc(doc.cm.doc);
codeMirror.on('beforeChange', this.codeMirrorBeforeChange);
codeMirror.on('changes', this.codeMirrorChanges);
doc.on('op', this.shareDBOp);
doc.on('del', this.shareDBDel);
doc.on('error', this.shareDBError);
}
/**
* Stops listening for changes from the CodeMirror instance and the ShareDB document.
*/
detachDoc() {
var doc = this.doc;
if (!doc) {
return;
}
doc.cm.version = doc.version;
var codeMirror = this.codeMirror;
codeMirror.off('beforeChange', this.codeMirrorBeforeChange);
codeMirror.off('changes', this.codeMirrorChanges);
doc.removeListener('op', this.shareDBOp);
doc.removeListener('del', this.shareDBDel);
doc.removeListener('error', this.shareDBError);
delete this.doc;
this.log('ShareDBCodeMirror: unsubscribed from doc');
}
/**
* Asserts that the CodeMirror instance's value matches the document's content
* in order to ensure that the two copies haven't diverged.
*/
assertValue() {
var expectedValue = this.doc.data[this.key];
var editorValue = this.codeMirror.getValue();
if (expectedValue !== editorValue) {
console.error('ShareDBCodeMirror: value in CodeMirror does not match expected value:', '\n\nExpected value:\n', expectedValue, '\n\nEditor value:\n', editorValue);
this.suppressChange = true;
this.codeMirror.setValue(expectedValue);
this.suppressChange = false;
}
}
/**
* Applies the changes represented by the given array of OT operations. It
* may be ignored if they are an echo of the most recently submitted local
* operations.
*/
onRemoteChange(ops, source) {
if (source) {
return;
}
this.log('ShareDBCodeMirror: applying ops', ops);
this.suppressChange = true;
for (var part of ops) {
if (!(part.p && part.p.length === 1 && part.p[0] === this.key && part.t === 'text0')) {
this.log('ShareDBCodeMirror: ignoring op because of path or type:', part);
continue;
}
var op = part.o;
var codeMirror = this.codeMirror;
if (op.length === 2 && op[0].d && op[1].i && op[0].p === op[1].p) {
// replace operation
var from = codeMirror.posFromIndex(op[0].p);
var to = codeMirror.posFromIndex(op[0].p + op[0].d.length);
codeMirror.replaceRange(op[1].i, from, to);
} else {
for (part of op) {
var from = codeMirror.posFromIndex(part.p);
if (part.d) {
// delete operation
var to = codeMirror.posFromIndex(part.p + part.d.length);
codeMirror.replaceRange('', from, to);
} else if (part.i) {
// insert operation
codeMirror.replaceRange(part.i, from);
}
}
}
}
this.suppressChange = false;
this.assertValue();
}
onDocDelete(data, source) {
this.detachDoc();
this.codeMirror.setValue('Document deleted');
}
onDocError(error) {
this.errorHandler(error);
}
/**
* Callback for the CodeMirror `beforeChange` event. It may be ignored if it
* is an echo of the most recently applied remote operations, otherwise it
* collects all the operations which are later sent to the server.
*/
beforeLocalChange(codeMirror, change) {
if (this.suppressChange) {
return;
}
if (!this.ops) {
this.ops = [];
}
var index = this.codeMirror.indexFromPos(change.from);
if (change.from !== change.to) {
// delete operation
var deleted = codeMirror.getRange(change.from, change.to);
this.ops.push({p: index, d: deleted});
}
if (change.text[0] !== '' || change.text.length > 0) {
// insert operation
var inserted = change.text.join('\n');
this.ops.push({p: index, i: inserted});
}
}
/**
* Callback for the CodeMirror `changes` event. It may be ignored if it is
* an echo of the most recently applied remote operations, otherwise it
* sends the previously collected operations to the server.
*/
afterLocalChanges(codeMirror, changes) {
if (this.suppressChange) {
return;
}
var op = [{p: [this.key], t: 'text0', o: this.ops}];
delete this.ops;
this.log('ShareDBCodeMirror: submitting op', op);
this.doc.submitOp(op, (error) => {
if (error) {
this.errorHandler(error);
}
});
this.assertValue();
}
}
module.exports = ShareDBCodeMirror;