-
Notifications
You must be signed in to change notification settings - Fork 0
/
diffsync.js
1302 lines (1181 loc) · 41.3 KB
/
diffsync.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
var diffsync = (typeof(module) != 'undefined') ? module.exports : {}
diffsync.version = 1039
diffsync.port = 60607
diffsync.create_client = function (options) {
// options: ws_url, channel, get_text, get_range, on_text, on_range
var self = {}
self.on_change = null
self.update_range = null
self.on_window_closing = null
var uid = guid()
var minigit = diffsync.create_minigit()
var unacknowledged_commits = {}
window.addEventListener('beforeunload', function () {
if (self.on_window_closing) self.on_window_closing()
})
function reconnect() {
console.log('connecting...')
var ws = new WebSocket(options.ws_url)
function send(o) {
o.v = diffsync.version
o.uid = uid
o.channel = options.channel
try {
ws.send(JSON.stringify(o))
} catch (e) {}
}
self.on_window_closing = function () {
send({ close : true })
}
ws.onopen = function () {
send({ join : true })
on_pong()
}
var pong_timer = null
function on_pong() {
clearTimeout(pong_timer)
setTimeout(function () {
send({ ping : true })
pong_timer = setTimeout(function () {
console.log('no pong came!!')
if (ws) {
ws = null
reconnect()
}
}, 4000)
}, 3000)
}
ws.onclose = function () {
console.log('connection closed...')
if (ws) {
ws = null
reconnect()
}
}
var sent_unacknowledged_commits = false
ws.onmessage = function (event) {
if (!ws) { return }
var o = JSON.parse(event.data)
if (o.pong) { return on_pong() }
console.log('message: ' + event.data)
if (o.commits) {
self.on_change()
minigit.merge(o.commits)
var patch = get_diff_patch(options.get_text(), minigit.cache)
options.on_text(minigit.cache, map_array(options.get_range(), function (x) {
each(patch, function (p) {
if (p[0] < x) {
if (p[0] + p[1] <= x) {
x += -p[1] + p[2].length
} else {
x = p[0] + p[2].length
}
} else return false
})
return x
}))
if (o.welcome) {
each(extend(o.commits, minigit.get_ancestors(o.commits)), function (_, id) {
delete unacknowledged_commits[id]
})
if (Object.keys(unacknowledged_commits).length > 0) {
send({ commits : unacknowledged_commits })
}
sent_unacknowledged_commits = true
}
send({ leaves : minigit.leaves })
}
if (o.range && options.on_range) options.on_range(o.range)
}
self.on_change = function () {
var cs = minigit.commit(options.get_text())
if (cs) {
extend(unacknowledged_commits, cs)
if (sent_unacknowledged_commits) {
send({ commits : cs })
}
}
}
self.update_range = function () {
send({ range : options.get_range() })
}
}
reconnect()
return self
}
diffsync.create_server = function (options) {
// options: wss, initial_data, on_change
var self = {}
self.channels = {}
function new_channel(name) {
return self.channels[name] = {
name : name,
minigit : diffsync.create_minigit(),
members : {}
}
}
function get_channel(name) {
return self.channels[name] || new_channel(name)
}
var users_to_sockets = {}
if (options.initial_data) {
each(options.initial_data, function (data, channel) {
var c = get_channel(channel)
c.minigit.merge(data.commits)
extend(c.members, data.members)
})
}
options.wss.on('connection', function connection(ws) {
console.log('new connection')
ws.on('close', function () {
each(users_to_sockets, function (_ws, uid) {
if (_ws == ws) {
delete users_to_sockets[uid]
}
})
})
ws.on('message', function (message) {
var o = JSON.parse(message)
if (!(o.v && o.v >= diffsync.version)) { return }
if (o.ping) { return try_send(ws, JSON.stringify({ pong : true })) }
console.log('message: ' + message)
var uid = o.uid
users_to_sockets[uid] = ws
var channel = get_channel(o.channel)
var changes = { channel : channel.name, commits : {}, members : {} }
if (!channel.members[uid]) channel.members[uid] = { do_not_delete : {}, last_sent : 0 }
channel.members[uid].last_seen = Date.now()
changes.members[uid] = channel.members[uid]
function try_send(ws, message) {
try {
ws.send(message)
} catch (e) {}
}
function send_to_all_but_me(message) {
each(channel.members, function (_, them) {
if (them != uid) {
try_send(users_to_sockets[them], message)
}
})
}
if (o.join) {
try_send(ws, JSON.stringify({ commits : channel.minigit.commits, welcome : true }))
}
if (o.commits) {
var new_commits = {}
each(o.commits, function (c, id) {
if (!channel.minigit.commits[id]) {
new_commits[id] = c
changes.commits[id] = c
}
})
channel.minigit.merge(new_commits)
var new_message = JSON.stringify({
channel : channel.name,
commits : new_commits
})
leaves = channel.minigit.get_leaves(new_commits)
var now = Date.now()
each(channel.members, function (m, them) {
if (them != uid) {
if (m.last_seen > m.last_sent) {
m.last_sent = now
changes.members[them] = m
} else if (m.last_sent < now - 3000) {
return
}
extend(m.do_not_delete, leaves)
try_send(users_to_sockets[them], new_message)
}
})
if (!o.leaves) o.leaves = channel.minigit.get_leaves(o.commits)
}
if (o.leaves) {
extend(channel.members[uid].do_not_delete, o.leaves)
each(channel.minigit.get_ancestors(o.leaves), function (_, id) {
delete channel.members[uid].do_not_delete[id]
})
changes.members[uid] = channel.members[uid]
var necessary = {}
each(channel.members, function (m) {
extend(necessary, m.do_not_delete)
})
extend(changes.commits, channel.minigit.remove_unnecessary(necessary))
}
if (o.range)
send_to_all_but_me(message)
if (o.close) {
delete channel.members[uid]
changes.members[uid] = null
}
if (options.on_change) options.on_change(changes)
})
})
return self
}
///////////////
diffsync.create_minigit = function () {
var self = {
commits : {},
to_children : {},
commit_cache : {},
leaves : {},
cache : ''
}
self.remove_unnecessary = function (spare_us) {
var affected = {}
while (true) {
var found = false
each(self.commits, function (c, id) {
if (spare_us[id]) { return }
var aff = self.remove(id)
if (aff) {
extend(affected, aff)
found = true
}
})
if (!found) break
}
return affected
}
self.remove = function (id) {
var keys = Object.keys(self.to_children[id])
if (keys.length == 1) {
var affected = {}
var being_removed = self.commits[id]
var c_id = keys[0]
var c = self.commits[c_id]
self.get_text(c_id)
each(being_removed.to_parents, function (_, id) {
self.get_text(id)
})
delete self.commits[id]
delete self.commit_cache[id]
delete c.to_parents[id]
delete c.from_parents[id]
affected[id] = null
each(being_removed.to_parents, function (_, id) {
c.to_parents[id] = get_diff_patch(self.get_text(c_id), self.get_text(id))
c.from_parents[id] = get_diff_patch(self.get_text(id), self.get_text(c_id))
})
if (Object.keys(c.to_parents).length == 0) {
c.text = self.get_text(c_id)
}
affected[c_id] = c
self.calc_children()
return affected
}
}
self.commit = function (s) {
if (s == self.cache) { return }
var c = {
to_parents : {},
from_parents : {}
}
if (Object.keys(self.leaves).length == 0) {
c.text = s
} else {
each(self.leaves, function (_, leaf) {
c.to_parents[leaf] = get_diff_patch(s, self.get_text(leaf))
c.from_parents[leaf] = get_diff_patch(self.get_text(leaf), s)
})
}
var id = guid()
self.commits[id] = c
self.calc_children()
self.leaves = {}
self.leaves[id] = true
self.commit_cache[id] = s
self.cache = s
self.purge_cache()
var cs = {}
cs[id] = c
return cs
}
self.merge = function (cs) {
each(cs, function (c, id) {
if (!self.commits[id]) {
self.commits[id] = c
} else {
if (c.text) self.commits[id].text = c.text
extend(self.commits[id].to_parents, c.to_parents)
extend(self.commits[id].from_parents, c.from_parents)
}
})
self.calc_children()
self.leaves = self.get_leaves()
self.cache = self.rec_merge(self.leaves)
self.purge_cache()
return self.cache
}
self.calc_children = function () {
self.to_children = {}
each(self.commits, function (c, id) {
self.to_children[id] = {}
})
each(self.commits, function (c, id) {
each(c.from_parents, function (d, p_id) {
self.to_children[p_id][id] = d
})
})
}
self.purge_cache = function () {
each(self.commits, function (c, id) {
if (Object.keys(c.to_parents).length > 0 && !self.leaves[id]) {
delete self.commit_cache[id]
}
})
}
self.get_text = function (id) {
if (self.commit_cache[id] != null) return self.commit_cache[id]
var frontier = [id]
var back_pointers = {}
back_pointers[id] = id
while (true) {
var next = frontier.shift()
if (!next) { return null }
var c_id = next
var c = self.commits[c_id]
var text = (c.text != null) ? c.text : self.commit_cache[c_id]
if (text != null) {
var snowball = text
while (true) {
if (next == id) {
return self.commit_cache[id] = snowball
}
next = back_pointers[next]
snowball = apply_diff_patch(snowball, c.to_parents[next] || self.to_children[c_id][next])
c_id = next
c = self.commits[c_id]
}
}
each(c.to_parents, function (_, id) {
if (!back_pointers[id]) {
back_pointers[id] = next
frontier.push(id)
}
})
each(self.to_children[c_id], function (_, id) {
if (!back_pointers[id]) {
back_pointers[id] = next
frontier.push(id)
}
})
}
}
self.rec_merge = function (these) {
these = Object.keys(these)
if (these.length == 0) { return '' }
var r = self.get_text(these[0])
if (these.length == 1) { return r }
var r_ancestors = self.get_ancestors(these[0])
for (var i = 1; i < these.length; i++) {
var i_ancestors = self.get_ancestors(these[i])
var o = self.rec_merge(self.get_leaves(intersection(r_ancestors, i_ancestors)))
r = apply_diff_patch(o, get_merged_diff_patch(r, self.get_text(these[i]), o))
extend(r_ancestors, i_ancestors)
}
return r
}
self.get_leaves = function (commits) {
if (!commits) commits = self.commits
var leaves = {}
each(commits, function (_, id) { leaves[id] = true })
each(commits, function (c) {
each(c.to_parents, function (_, p) {
delete leaves[p]
})
})
return leaves
}
self.get_ancestors = function (id_or_set) {
var frontier = null
if (typeof(id_or_set) == 'object') {
frontier = Object.keys(id_or_set)
} else {
frontier = [id_or_set]
}
var ancestors = {}
while (frontier.length > 0) {
var next = frontier.shift()
each(self.commits[next].to_parents, function (_, p) {
if (!ancestors[p]) {
ancestors[p] = self.commits[p]
frontier.push(p)
}
})
}
return ancestors
}
return self
}
///////////////
function guid() {
var x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var s = []
for (var i = 0; i < 15; i++) {
s.push(x[Math.floor(Math.random() * x.length)])
}
return s.join('')
}
function each(o, cb) {
if (o instanceof Array) {
for (var i = 0; i < o.length; i++) {
if (cb(o[i], i, o) == false)
return false
}
} else {
for (var k in o) {
if (o.hasOwnProperty(k)) {
if (cb(o[k], k, o) == false)
return false
}
}
}
return true
}
function map_array(a, f) {
var b = []
each(a, function (v, k) { b[k] = f(v) })
return b
}
function extend(a, b) {
each(b, function (x, key) { a[key] = x })
return a
}
function intersection(a, b) {
var common = {}
each(a, function (_, x) {
if (b[x]) {
common[x] = a[x]
}
})
return common
}
///////////////
var DIFF_DELETE = -1;
var DIFF_INSERT = 1;
var DIFF_EQUAL = 0;
function get_merged_diff_patch(a, b, o) {
var a_diff = get_diff_patch(o, a)
var b_diff = get_diff_patch(o, b)
var ds = []
var prev_d = null
while (a_diff.length > 0 || b_diff.length > 0) {
var d = a_diff.length == 0 ?
b_diff.shift() :
b_diff.length == 0 ?
a_diff.shift() :
a_diff[0][0] < b_diff[0][0] ?
a_diff.shift() :
a_diff[0][0] > b_diff[0][0] ?
b_diff.shift() :
a_diff[0][2] < b_diff[0][2] ?
a_diff.shift() :
b_diff.shift()
if (prev_d && d[0] < prev_d[0] + prev_d[1]) {
if (d[0] + d[1] > prev_d[0] + prev_d[1]) {
prev_d[1] = d[0] + d[1] - prev_d[0]
}
prev_d[2] += d[2]
} else {
ds.push(d)
prev_d = d
}
}
return ds
}
function apply_diff_patch(s, diff) {
var offset = 0
for (var i = 0; i < diff.length; i++) {
var d = diff[i]
s = s.slice(0, d[0] + offset) + d[2] + s.slice(d[0] + offset + d[1])
offset += d[2].length - d[1]
}
return s
}
function diff_convert_to_my_format(d) {
var x = []
var ii = 0
for (var i = 0; i < d.length; i++) {
var dd = d[i]
if (dd[0] == DIFF_EQUAL) {
ii += dd[1].length
continue
}
var xx = [ii, 0, '']
if (dd[0] == DIFF_INSERT) {
xx[2] = dd[1]
} else if (dd[0] == DIFF_DELETE) {
xx[1] = dd[1].length
ii += xx[1]
}
if (i + 1 < d.length) {
dd = d[i + 1]
if (dd[0] != DIFF_EQUAL) {
if (dd[0] == DIFF_INSERT) {
xx[2] = dd[1]
} else if (dd[0] == DIFF_DELETE) {
xx[1] = dd[1].length
ii += xx[1]
}
i++
}
}
x.push(xx)
}
return x
}
function get_diff_patch(a, b) {
return diff_convert_to_my_format(diff_main(a, b))
}
diffsync.get_diff_patch = get_diff_patch
/**
* This library modifies the diff-patch-match library by Neil Fraser
* by removing the patch and match functionality and certain advanced
* options in the diff function. The original license is as follows:
*
* ===
*
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
// var DIFF_DELETE = -1;
// var DIFF_INSERT = 1;
// var DIFF_EQUAL = 0;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {Int} cursor_pos Expected edit position in text1 (optional)
* @return {Array} Array of diff tuples.
*/
function diff_main(text1, text2, cursor_pos) {
// Check for equality (speedup).
if (text1 == text2) {
if (text1) {
return [[DIFF_EQUAL, text1]];
}
return [];
}
// Check cursor_pos within bounds
if (cursor_pos < 0 || text1.length < cursor_pos) {
cursor_pos = null;
}
// Trim off common prefix (speedup).
var commonlength = diff_commonPrefix(text1, text2);
var commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = diff_commonSuffix(text1, text2);
var commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
var diffs = diff_compute_(text1, text2);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
diff_cleanupMerge(diffs);
if (cursor_pos != null) {
diffs = fix_cursor(diffs, cursor_pos);
}
return diffs;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @return {Array} Array of diff tuples.
*/
function diff_compute_(text1, text2) {
var diffs;
if (!text1) {
// Just add some text (speedup).
return [[DIFF_INSERT, text2]];
}
if (!text2) {
// Just delete some text (speedup).
return [[DIFF_DELETE, text1]];
}
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
var i = longtext.indexOf(shorttext);
if (i != -1) {
// Shorter text is inside the longer text (speedup).
diffs = [[DIFF_INSERT, longtext.substring(0, i)],
[DIFF_EQUAL, shorttext],
[DIFF_INSERT, longtext.substring(i + shorttext.length)]];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
// Check to see if the problem can be split in two.
var hm = diff_halfMatch_(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
var text2_b = hm[3];
var mid_common = hm[4];
// Send both pairs off for separate processing.
var diffs_a = diff_main(text1_a, text2_a);
var diffs_b = diff_main(text1_b, text2_b);
// Merge the results.
return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
}
return diff_bisect_(text1, text2);
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @return {Array} Array of diff tuples.
* @private
*/
function diff_bisect_(text1, text2) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
var max_d = Math.ceil((text1_length + text2_length) / 2);
var v_offset = max_d;
var v_length = 2 * max_d;
var v1 = new Array(v_length);
var v2 = new Array(v_length);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (var x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
var delta = text1_length - text2_length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
var front = (delta % 2 != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
var k1start = 0;
var k1end = 0;
var k2start = 0;
var k2end = 0;
for (var d = 0; d < max_d; d++) {
// Walk the front path one step.
for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
var k1_offset = v_offset + k1;
var x1;
if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
var y1 = x1 - k1;
while (x1 < text1_length && y1 < text2_length &&
text1.charAt(x1) == text2.charAt(y1)) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
var k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
// Mirror x2 onto top-left coordinate system.
var x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
// Overlap detected.
return diff_bisectSplit_(text1, text2, x1, y1);
}
}
}
}
// Walk the reverse path one step.
for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
var k2_offset = v_offset + k2;
var x2;
if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
var y2 = x2 - k2;
while (x2 < text1_length && y2 < text2_length &&
text1.charAt(text1_length - x2 - 1) ==
text2.charAt(text2_length - y2 - 1)) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
var k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
var x1 = v1[k1_offset];
var y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
return diff_bisectSplit_(text1, text2, x1, y1);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @return {Array} Array of diff tuples.
*/
function diff_bisectSplit_(text1, text2, x, y) {
var text1a = text1.substring(0, x);
var text2a = text2.substring(0, y);
var text1b = text1.substring(x);
var text2b = text2.substring(y);
// Compute both diffs serially.
var diffs = diff_main(text1a, text2a);
var diffsb = diff_main(text1b, text2b);
return diffs.concat(diffsb);
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
function diff_commonPrefix(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerstart = 0;
while (pointermin < pointermid) {
if (text1.substring(pointerstart, pointermid) ==
text2.substring(pointerstart, pointermid)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
function diff_commonSuffix(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 ||
text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerend = 0;
while (pointermin < pointermid) {
if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
text2.substring(text2.length - pointermid, text2.length - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
*/
function diff_halfMatch_(text1, text2) {
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diff_halfMatchI_(longtext, shorttext, i) {
// Start with a 1/4 length substring at position i as a seed.
var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
var j = -1;
var best_common = '';
var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
var prefixLength = diff_commonPrefix(longtext.substring(i),