-
Notifications
You must be signed in to change notification settings - Fork 12
/
opentok-editor.js
2202 lines (1908 loc) · 69.6 KB
/
opentok-editor.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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* /\
* / \ ot 0.0.15
* / \ http://operational-transformation.github.com
* \ /
* \ / (c) 2012-2016 Tim Baumann <tim@timbaumann.info> (http://timbaumann.info)
* \/ ot may be freely distributed under the MIT license.
*/
if (typeof ot === 'undefined') {
// Export for browsers
var ot = {};
}
ot.TextOperation = (function () {
'use strict';
// Constructor for new operations.
function TextOperation () {
if (!this || this.constructor !== TextOperation) {
// => function was called without 'new'
return new TextOperation();
}
// When an operation is applied to an input string, you can think of this as
// if an imaginary cursor runs over the entire string and skips over some
// parts, deletes some parts and inserts characters at some positions. These
// actions (skip/delete/insert) are stored as an array in the "ops" property.
this.ops = [];
// An operation's baseLength is the length of every string the operation
// can be applied to.
this.baseLength = 0;
// The targetLength is the length of every string that results from applying
// the operation on a valid input string.
this.targetLength = 0;
}
TextOperation.prototype.equals = function (other) {
if (this.baseLength !== other.baseLength) { return false; }
if (this.targetLength !== other.targetLength) { return false; }
if (this.ops.length !== other.ops.length) { return false; }
for (var i = 0; i < this.ops.length; i++) {
if (this.ops[i] !== other.ops[i]) { return false; }
}
return true;
};
// Operation are essentially lists of ops. There are three types of ops:
//
// * Retain ops: Advance the cursor position by a given number of characters.
// Represented by positive ints.
// * Insert ops: Insert a given string at the current cursor position.
// Represented by strings.
// * Delete ops: Delete the next n characters. Represented by negative ints.
var isRetain = TextOperation.isRetain = function (op) {
return typeof op === 'number' && op > 0;
};
var isInsert = TextOperation.isInsert = function (op) {
return typeof op === 'string';
};
var isDelete = TextOperation.isDelete = function (op) {
return typeof op === 'number' && op < 0;
};
// After an operation is constructed, the user of the library can specify the
// actions of an operation (skip/insert/delete) with these three builder
// methods. They all return the operation for convenient chaining.
// Skip over a given number of characters.
TextOperation.prototype.retain = function (n) {
if (typeof n !== 'number') {
throw new Error("retain expects an integer");
}
if (n === 0) { return this; }
this.baseLength += n;
this.targetLength += n;
if (isRetain(this.ops[this.ops.length-1])) {
// The last op is a retain op => we can merge them into one op.
this.ops[this.ops.length-1] += n;
} else {
// Create a new op.
this.ops.push(n);
}
return this;
};
// Insert a string at the current position.
TextOperation.prototype.insert = function (str) {
if (typeof str !== 'string') {
throw new Error("insert expects a string");
}
if (str === '') { return this; }
this.targetLength += str.length;
var ops = this.ops;
if (isInsert(ops[ops.length-1])) {
// Merge insert op.
ops[ops.length-1] += str;
} else if (isDelete(ops[ops.length-1])) {
// It doesn't matter when an operation is applied whether the operation
// is delete(3), insert("something") or insert("something"), delete(3).
// Here we enforce that in this case, the insert op always comes first.
// This makes all operations that have the same effect when applied to
// a document of the right length equal in respect to the `equals` method.
if (isInsert(ops[ops.length-2])) {
ops[ops.length-2] += str;
} else {
ops[ops.length] = ops[ops.length-1];
ops[ops.length-2] = str;
}
} else {
ops.push(str);
}
return this;
};
// Delete a string at the current position.
TextOperation.prototype['delete'] = function (n) {
if (typeof n === 'string') { n = n.length; }
if (typeof n !== 'number') {
throw new Error("delete expects an integer or a string");
}
if (n === 0) { return this; }
if (n > 0) { n = -n; }
this.baseLength -= n;
if (isDelete(this.ops[this.ops.length-1])) {
this.ops[this.ops.length-1] += n;
} else {
this.ops.push(n);
}
return this;
};
// Tests whether this operation has no effect.
TextOperation.prototype.isNoop = function () {
return this.ops.length === 0 || (this.ops.length === 1 && isRetain(this.ops[0]));
};
// Pretty printing.
TextOperation.prototype.toString = function () {
// map: build a new array by applying a function to every element in an old
// array.
var map = Array.prototype.map || function (fn) {
var arr = this;
var newArr = [];
for (var i = 0, l = arr.length; i < l; i++) {
newArr[i] = fn(arr[i]);
}
return newArr;
};
return map.call(this.ops, function (op) {
if (isRetain(op)) {
return "retain " + op;
} else if (isInsert(op)) {
return "insert '" + op + "'";
} else {
return "delete " + (-op);
}
}).join(', ');
};
// Converts operation into a JSON value.
TextOperation.prototype.toJSON = function () {
return this.ops;
};
// Converts a plain JS object into an operation and validates it.
TextOperation.fromJSON = function (ops) {
var o = new TextOperation();
for (var i = 0, l = ops.length; i < l; i++) {
var op = ops[i];
if (isRetain(op)) {
o.retain(op);
} else if (isInsert(op)) {
o.insert(op);
} else if (isDelete(op)) {
o['delete'](op);
} else {
throw new Error("unknown operation: " + JSON.stringify(op));
}
}
return o;
};
// Apply an operation to a string, returning a new string. Throws an error if
// there's a mismatch between the input string and the operation.
TextOperation.prototype.apply = function (str) {
var operation = this;
if (str.length !== operation.baseLength) {
throw new Error("The operation's base length must be equal to the string's length.");
}
var newStr = [], j = 0;
var strIndex = 0;
var ops = this.ops;
for (var i = 0, l = ops.length; i < l; i++) {
var op = ops[i];
if (isRetain(op)) {
if (strIndex + op > str.length) {
throw new Error("Operation can't retain more characters than are left in the string.");
}
// Copy skipped part of the old string.
newStr[j++] = str.slice(strIndex, strIndex + op);
strIndex += op;
} else if (isInsert(op)) {
// Insert string.
newStr[j++] = op;
} else { // delete op
strIndex -= op;
}
}
if (strIndex !== str.length) {
throw new Error("The operation didn't operate on the whole string.");
}
return newStr.join('');
};
// Computes the inverse of an operation. The inverse of an operation is the
// operation that reverts the effects of the operation, e.g. when you have an
// operation 'insert("hello "); skip(6);' then the inverse is 'delete("hello ");
// skip(6);'. The inverse should be used for implementing undo.
TextOperation.prototype.invert = function (str) {
var strIndex = 0;
var inverse = new TextOperation();
var ops = this.ops;
for (var i = 0, l = ops.length; i < l; i++) {
var op = ops[i];
if (isRetain(op)) {
inverse.retain(op);
strIndex += op;
} else if (isInsert(op)) {
inverse['delete'](op.length);
} else { // delete op
inverse.insert(str.slice(strIndex, strIndex - op));
strIndex -= op;
}
}
return inverse;
};
// Compose merges two consecutive operations into one operation, that
// preserves the changes of both. Or, in other words, for each input string S
// and a pair of consecutive operations A and B,
// apply(apply(S, A), B) = apply(S, compose(A, B)) must hold.
TextOperation.prototype.compose = function (operation2) {
var operation1 = this;
if (operation1.targetLength !== operation2.baseLength) {
throw new Error("The base length of the second operation has to be the target length of the first operation");
}
var operation = new TextOperation(); // the combined operation
var ops1 = operation1.ops, ops2 = operation2.ops; // for fast access
var i1 = 0, i2 = 0; // current index into ops1 respectively ops2
var op1 = ops1[i1++], op2 = ops2[i2++]; // current ops
while (true) {
// Dispatch on the type of op1 and op2
if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
// end condition: both ops1 and ops2 have been processed
break;
}
if (isDelete(op1)) {
operation['delete'](op1);
op1 = ops1[i1++];
continue;
}
if (isInsert(op2)) {
operation.insert(op2);
op2 = ops2[i2++];
continue;
}
if (typeof op1 === 'undefined') {
throw new Error("Cannot compose operations: first operation is too short.");
}
if (typeof op2 === 'undefined') {
throw new Error("Cannot compose operations: first operation is too long.");
}
if (isRetain(op1) && isRetain(op2)) {
if (op1 > op2) {
operation.retain(op2);
op1 = op1 - op2;
op2 = ops2[i2++];
} else if (op1 === op2) {
operation.retain(op1);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation.retain(op1);
op2 = op2 - op1;
op1 = ops1[i1++];
}
} else if (isInsert(op1) && isDelete(op2)) {
if (op1.length > -op2) {
op1 = op1.slice(-op2);
op2 = ops2[i2++];
} else if (op1.length === -op2) {
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
op2 = op2 + op1.length;
op1 = ops1[i1++];
}
} else if (isInsert(op1) && isRetain(op2)) {
if (op1.length > op2) {
operation.insert(op1.slice(0, op2));
op1 = op1.slice(op2);
op2 = ops2[i2++];
} else if (op1.length === op2) {
operation.insert(op1);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation.insert(op1);
op2 = op2 - op1.length;
op1 = ops1[i1++];
}
} else if (isRetain(op1) && isDelete(op2)) {
if (op1 > -op2) {
operation['delete'](op2);
op1 = op1 + op2;
op2 = ops2[i2++];
} else if (op1 === -op2) {
operation['delete'](op2);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation['delete'](op1);
op2 = op2 + op1;
op1 = ops1[i1++];
}
} else {
throw new Error(
"This shouldn't happen: op1: " +
JSON.stringify(op1) + ", op2: " +
JSON.stringify(op2)
);
}
}
return operation;
};
function getSimpleOp (operation, fn) {
var ops = operation.ops;
var isRetain = TextOperation.isRetain;
switch (ops.length) {
case 1:
return ops[0];
case 2:
return isRetain(ops[0]) ? ops[1] : (isRetain(ops[1]) ? ops[0] : null);
case 3:
if (isRetain(ops[0]) && isRetain(ops[2])) { return ops[1]; }
}
return null;
}
function getStartIndex (operation) {
if (isRetain(operation.ops[0])) { return operation.ops[0]; }
return 0;
}
// When you use ctrl-z to undo your latest changes, you expect the program not
// to undo every single keystroke but to undo your last sentence you wrote at
// a stretch or the deletion you did by holding the backspace key down. This
// This can be implemented by composing operations on the undo stack. This
// method can help decide whether two operations should be composed. It
// returns true if the operations are consecutive insert operations or both
// operations delete text at the same position. You may want to include other
// factors like the time since the last change in your decision.
TextOperation.prototype.shouldBeComposedWith = function (other) {
if (this.isNoop() || other.isNoop()) { return true; }
var startA = getStartIndex(this), startB = getStartIndex(other);
var simpleA = getSimpleOp(this), simpleB = getSimpleOp(other);
if (!simpleA || !simpleB) { return false; }
if (isInsert(simpleA) && isInsert(simpleB)) {
return startA + simpleA.length === startB;
}
if (isDelete(simpleA) && isDelete(simpleB)) {
// there are two possibilities to delete: with backspace and with the
// delete key.
return (startB - simpleB === startA) || startA === startB;
}
return false;
};
// Decides whether two operations should be composed with each other
// if they were inverted, that is
// `shouldBeComposedWith(a, b) = shouldBeComposedWithInverted(b^{-1}, a^{-1})`.
TextOperation.prototype.shouldBeComposedWithInverted = function (other) {
if (this.isNoop() || other.isNoop()) { return true; }
var startA = getStartIndex(this), startB = getStartIndex(other);
var simpleA = getSimpleOp(this), simpleB = getSimpleOp(other);
if (!simpleA || !simpleB) { return false; }
if (isInsert(simpleA) && isInsert(simpleB)) {
return startA + simpleA.length === startB || startA === startB;
}
if (isDelete(simpleA) && isDelete(simpleB)) {
return startB - simpleB === startA;
}
return false;
};
// Transform takes two operations A and B that happened concurrently and
// produces two operations A' and B' (in an array) such that
// `apply(apply(S, A), B') = apply(apply(S, B), A')`. This function is the
// heart of OT.
TextOperation.transform = function (operation1, operation2) {
if (operation1.baseLength !== operation2.baseLength) {
throw new Error("Both operations have to have the same base length");
}
var operation1prime = new TextOperation();
var operation2prime = new TextOperation();
var ops1 = operation1.ops, ops2 = operation2.ops;
var i1 = 0, i2 = 0;
var op1 = ops1[i1++], op2 = ops2[i2++];
while (true) {
// At every iteration of the loop, the imaginary cursor that both
// operation1 and operation2 have that operates on the input string must
// have the same position in the input string.
if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
// end condition: both ops1 and ops2 have been processed
break;
}
// next two cases: one or both ops are insert ops
// => insert the string in the corresponding prime operation, skip it in
// the other one. If both op1 and op2 are insert ops, prefer op1.
if (isInsert(op1)) {
operation1prime.insert(op1);
operation2prime.retain(op1.length);
op1 = ops1[i1++];
continue;
}
if (isInsert(op2)) {
operation1prime.retain(op2.length);
operation2prime.insert(op2);
op2 = ops2[i2++];
continue;
}
if (typeof op1 === 'undefined') {
throw new Error("Cannot compose operations: first operation is too short.");
}
if (typeof op2 === 'undefined') {
throw new Error("Cannot compose operations: first operation is too long.");
}
var minl;
if (isRetain(op1) && isRetain(op2)) {
// Simple case: retain/retain
if (op1 > op2) {
minl = op2;
op1 = op1 - op2;
op2 = ops2[i2++];
} else if (op1 === op2) {
minl = op2;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = op1;
op2 = op2 - op1;
op1 = ops1[i1++];
}
operation1prime.retain(minl);
operation2prime.retain(minl);
} else if (isDelete(op1) && isDelete(op2)) {
// Both operations delete the same string at the same position. We don't
// need to produce any operations, we just skip over the delete ops and
// handle the case that one operation deletes more than the other.
if (-op1 > -op2) {
op1 = op1 - op2;
op2 = ops2[i2++];
} else if (op1 === op2) {
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
op2 = op2 - op1;
op1 = ops1[i1++];
}
// next two cases: delete/retain and retain/delete
} else if (isDelete(op1) && isRetain(op2)) {
if (-op1 > op2) {
minl = op2;
op1 = op1 + op2;
op2 = ops2[i2++];
} else if (-op1 === op2) {
minl = op2;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = -op1;
op2 = op2 + op1;
op1 = ops1[i1++];
}
operation1prime['delete'](minl);
} else if (isRetain(op1) && isDelete(op2)) {
if (op1 > -op2) {
minl = -op2;
op1 = op1 + op2;
op2 = ops2[i2++];
} else if (op1 === -op2) {
minl = op1;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = op1;
op2 = op2 + op1;
op1 = ops1[i1++];
}
operation2prime['delete'](minl);
} else {
throw new Error("The two operations aren't compatible");
}
}
return [operation1prime, operation2prime];
};
return TextOperation;
}());
// Export for CommonJS
if (typeof module === 'object') {
module.exports = ot.TextOperation;
}
if (typeof ot === 'undefined') {
// Export for browsers
var ot = {};
}
ot.Selection = (function (global) {
'use strict';
var TextOperation = global.ot ? global.ot.TextOperation : require('./text-operation');
// Range has `anchor` and `head` properties, which are zero-based indices into
// the document. The `anchor` is the side of the selection that stays fixed,
// `head` is the side of the selection where the cursor is. When both are
// equal, the range represents a cursor.
function Range (anchor, head) {
this.anchor = anchor;
this.head = head;
}
Range.fromJSON = function (obj) {
return new Range(obj.anchor, obj.head);
};
Range.prototype.equals = function (other) {
return this.anchor === other.anchor && this.head === other.head;
};
Range.prototype.isEmpty = function () {
return this.anchor === this.head;
};
Range.prototype.transform = function (other) {
function transformIndex (index) {
var newIndex = index;
var ops = other.ops;
for (var i = 0, l = other.ops.length; i < l; i++) {
if (TextOperation.isRetain(ops[i])) {
index -= ops[i];
} else if (TextOperation.isInsert(ops[i])) {
newIndex += ops[i].length;
} else {
newIndex -= Math.min(index, -ops[i]);
index += ops[i];
}
if (index < 0) { break; }
}
return newIndex;
}
var newAnchor = transformIndex(this.anchor);
if (this.anchor === this.head) {
return new Range(newAnchor, newAnchor);
}
return new Range(newAnchor, transformIndex(this.head));
};
// A selection is basically an array of ranges. Every range represents a real
// selection or a cursor in the document (when the start position equals the
// end position of the range). The array must not be empty.
function Selection (ranges) {
this.ranges = ranges || [];
}
Selection.Range = Range;
// Convenience method for creating selections only containing a single cursor
// and no real selection range.
Selection.createCursor = function (position) {
return new Selection([new Range(position, position)]);
};
Selection.fromJSON = function (obj) {
var objRanges = obj.ranges || obj;
for (var i = 0, ranges = []; i < objRanges.length; i++) {
ranges[i] = Range.fromJSON(objRanges[i]);
}
return new Selection(ranges);
};
Selection.prototype.equals = function (other) {
if (this.position !== other.position) { return false; }
if (this.ranges.length !== other.ranges.length) { return false; }
// FIXME: Sort ranges before comparing them?
for (var i = 0; i < this.ranges.length; i++) {
if (!this.ranges[i].equals(other.ranges[i])) { return false; }
}
return true;
};
Selection.prototype.somethingSelected = function () {
for (var i = 0; i < this.ranges.length; i++) {
if (!this.ranges[i].isEmpty()) { return true; }
}
return false;
};
// Return the more current selection information.
Selection.prototype.compose = function (other) {
return other;
};
// Update the selection with respect to an operation.
Selection.prototype.transform = function (other) {
for (var i = 0, newRanges = []; i < this.ranges.length; i++) {
newRanges[i] = this.ranges[i].transform(other);
}
return new Selection(newRanges);
};
return Selection;
}(this));
// Export for CommonJS
if (typeof module === 'object') {
module.exports = ot.Selection;
}
if (typeof ot === 'undefined') {
// Export for browsers
var ot = {};
}
ot.WrappedOperation = (function (global) {
'use strict';
// A WrappedOperation contains an operation and corresponing metadata.
function WrappedOperation (operation, meta) {
this.wrapped = operation;
this.meta = meta;
}
WrappedOperation.prototype.apply = function () {
return this.wrapped.apply.apply(this.wrapped, arguments);
};
WrappedOperation.prototype.invert = function () {
var meta = this.meta;
return new WrappedOperation(
this.wrapped.invert.apply(this.wrapped, arguments),
meta && typeof meta === 'object' && typeof meta.invert === 'function' ?
meta.invert.apply(meta, arguments) : meta
);
};
// Copy all properties from source to target.
function copy (source, target) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
function composeMeta (a, b) {
if (a && typeof a === 'object') {
if (typeof a.compose === 'function') { return a.compose(b); }
var meta = {};
copy(a, meta);
copy(b, meta);
return meta;
}
return b;
}
WrappedOperation.prototype.compose = function (other) {
return new WrappedOperation(
this.wrapped.compose(other.wrapped),
composeMeta(this.meta, other.meta)
);
};
function transformMeta (meta, operation) {
if (meta && typeof meta === 'object') {
if (typeof meta.transform === 'function') {
return meta.transform(operation);
}
}
return meta;
}
WrappedOperation.transform = function (a, b) {
var transform = a.wrapped.constructor.transform;
var pair = transform(a.wrapped, b.wrapped);
return [
new WrappedOperation(pair[0], transformMeta(a.meta, b.wrapped)),
new WrappedOperation(pair[1], transformMeta(b.meta, a.wrapped))
];
};
return WrappedOperation;
}(this));
// Export for CommonJS
if (typeof module === 'object') {
module.exports = ot.WrappedOperation;
}
if (typeof ot === 'undefined') {
// Export for browsers
var ot = {};
}
ot.UndoManager = (function () {
'use strict';
var NORMAL_STATE = 'normal';
var UNDOING_STATE = 'undoing';
var REDOING_STATE = 'redoing';
// Create a new UndoManager with an optional maximum history size.
function UndoManager (maxItems) {
this.maxItems = maxItems || 50;
this.state = NORMAL_STATE;
this.dontCompose = false;
this.undoStack = [];
this.redoStack = [];
}
// Add an operation to the undo or redo stack, depending on the current state
// of the UndoManager. The operation added must be the inverse of the last
// edit. When `compose` is true, compose the operation with the last operation
// unless the last operation was alread pushed on the redo stack or was hidden
// by a newer operation on the undo stack.
UndoManager.prototype.add = function (operation, compose) {
if (this.state === UNDOING_STATE) {
this.redoStack.push(operation);
this.dontCompose = true;
} else if (this.state === REDOING_STATE) {
this.undoStack.push(operation);
this.dontCompose = true;
} else {
var undoStack = this.undoStack;
if (!this.dontCompose && compose && undoStack.length > 0) {
undoStack.push(operation.compose(undoStack.pop()));
} else {
undoStack.push(operation);
if (undoStack.length > this.maxItems) { undoStack.shift(); }
}
this.dontCompose = false;
this.redoStack = [];
}
};
function transformStack (stack, operation) {
var newStack = [];
var Operation = operation.constructor;
for (var i = stack.length - 1; i >= 0; i--) {
var pair = Operation.transform(stack[i], operation);
if (typeof pair[0].isNoop !== 'function' || !pair[0].isNoop()) {
newStack.push(pair[0]);
}
operation = pair[1];
}
return newStack.reverse();
}
// Transform the undo and redo stacks against a operation by another client.
UndoManager.prototype.transform = function (operation) {
this.undoStack = transformStack(this.undoStack, operation);
this.redoStack = transformStack(this.redoStack, operation);
};
// Perform an undo by calling a function with the latest operation on the undo
// stack. The function is expected to call the `add` method with the inverse
// of the operation, which pushes the inverse on the redo stack.
UndoManager.prototype.performUndo = function (fn) {
this.state = UNDOING_STATE;
if (this.undoStack.length === 0) { throw new Error("undo not possible"); }
fn(this.undoStack.pop());
this.state = NORMAL_STATE;
};
// The inverse of `performUndo`.
UndoManager.prototype.performRedo = function (fn) {
this.state = REDOING_STATE;
if (this.redoStack.length === 0) { throw new Error("redo not possible"); }
fn(this.redoStack.pop());
this.state = NORMAL_STATE;
};
// Is the undo stack not empty?
UndoManager.prototype.canUndo = function () {
return this.undoStack.length !== 0;
};
// Is the redo stack not empty?
UndoManager.prototype.canRedo = function () {
return this.redoStack.length !== 0;
};
// Whether the UndoManager is currently performing an undo.
UndoManager.prototype.isUndoing = function () {
return this.state === UNDOING_STATE;
};
// Whether the UndoManager is currently performing a redo.
UndoManager.prototype.isRedoing = function () {
return this.state === REDOING_STATE;
};
return UndoManager;
}());
// Export for CommonJS
if (typeof module === 'object') {
module.exports = ot.UndoManager;
}
// translation of https://github.com/djspiewak/cccp/blob/master/agent/src/main/scala/com/codecommit/cccp/agent/state.scala
if (typeof ot === 'undefined') {
var ot = {};
}
ot.Client = (function (global) {
'use strict';
// Client constructor
function Client (revision) {
this.revision = revision; // the next expected revision number
this.state = synchronized_; // start state
}
Client.prototype.setState = function (state) {
this.state = state;
};
// Call this method when the user changes the document.
Client.prototype.applyClient = function (operation) {
this.setState(this.state.applyClient(this, operation));
};
// Call this method with a new operation from the server
Client.prototype.applyServer = function (operation) {
this.revision++;
this.setState(this.state.applyServer(this, operation));
};
Client.prototype.serverAck = function () {
this.revision++;
this.setState(this.state.serverAck(this));
};
Client.prototype.serverReconnect = function () {
if (typeof this.state.resend === 'function') { this.state.resend(this); }
};
// Transforms a selection from the latest known server state to the current
// client state. For example, if we get from the server the information that
// another user's cursor is at position 3, but the server hasn't yet received
// our newest operation, an insertion of 5 characters at the beginning of the
// document, the correct position of the other user's cursor in our current
// document is 8.
Client.prototype.transformSelection = function (selection) {
return this.state.transformSelection(selection);
};
// Override this method.
Client.prototype.sendOperation = function (revision, operation) {
throw new Error("sendOperation must be defined in child class");
};
// Override this method.
Client.prototype.applyOperation = function (operation) {
throw new Error("applyOperation must be defined in child class");
};
// In the 'Synchronized' state, there is no pending operation that the client
// has sent to the server.
function Synchronized () {}
Client.Synchronized = Synchronized;
Synchronized.prototype.applyClient = function (client, operation) {
// When the user makes an edit, send the operation to the server and
// switch to the 'AwaitingConfirm' state
client.sendOperation(client.revision, operation);
return new AwaitingConfirm(operation);
};
Synchronized.prototype.applyServer = function (client, operation) {
// When we receive a new operation from the server, the operation can be
// simply applied to the current document
client.applyOperation(operation);
return this;
};
Synchronized.prototype.serverAck = function (client) {
throw new Error("There is no pending operation.");
};
// Nothing to do because the latest server state and client state are the same.
Synchronized.prototype.transformSelection = function (x) { return x; };
// Singleton
var synchronized_ = new Synchronized();
// In the 'AwaitingConfirm' state, there's one operation the client has sent
// to the server and is still waiting for an acknowledgement.
function AwaitingConfirm (outstanding) {
// Save the pending operation
this.outstanding = outstanding;
}
Client.AwaitingConfirm = AwaitingConfirm;
AwaitingConfirm.prototype.applyClient = function (client, operation) {
// When the user makes an edit, don't send the operation immediately,
// instead switch to 'AwaitingWithBuffer' state
return new AwaitingWithBuffer(this.outstanding, operation);
};
AwaitingConfirm.prototype.applyServer = function (client, operation) {
// This is another client's operation. Visualization:
//
// /\
// this.outstanding / \ operation
// / \
// \ /
// pair[1] \ / pair[0] (new outstanding)
// (can be applied \/
// to the client's
// current document)
var pair = operation.constructor.transform(this.outstanding, operation);
client.applyOperation(pair[1]);
return new AwaitingConfirm(pair[0]);
};
AwaitingConfirm.prototype.serverAck = function (client) {
// The client's operation has been acknowledged
// => switch to synchronized state
return synchronized_;
};
AwaitingConfirm.prototype.transformSelection = function (selection) {
return selection.transform(this.outstanding);
};
AwaitingConfirm.prototype.resend = function (client) {
// The confirm didn't come because the client was disconnected.
// Now that it has reconnected, we resend the outstanding operation.
client.sendOperation(client.revision, this.outstanding);
};
// In the 'AwaitingWithBuffer' state, the client is waiting for an operation
// to be acknowledged by the server while buffering the edits the user makes
function AwaitingWithBuffer (outstanding, buffer) {
// Save the pending operation and the user's edits since then
this.outstanding = outstanding;
this.buffer = buffer;
}
Client.AwaitingWithBuffer = AwaitingWithBuffer;
AwaitingWithBuffer.prototype.applyClient = function (client, operation) {
// Compose the user's changes onto the buffer
var newBuffer = this.buffer.compose(operation);
return new AwaitingWithBuffer(this.outstanding, newBuffer);
};