-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
2268 lines (1997 loc) · 105 KB
/
Copy pathtest.js
File metadata and controls
2268 lines (1997 loc) · 105 KB
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
// Tests for the parts of this extension that can run outside a browser.
//
// node test.js
//
// Chrome loads dt.js, dt-helpers.js and panel.js as *classic* scripts sharing
// one scope. Node normally loads files as modules, which hides the mistakes
// that actually break this extension, so everything here is compiled with
// vm.Script against a stub window instead. That is deliberate: `import.meta`
// is legal in a module, so checking dt.js as one would pass a file Chrome
// refuses to run.
//
// Three things are worth guarding: the transformations dt.js needs after every
// diamond-types rebuild, which have broken silently before; the history view's
// layout, which computes row geometry in plain arrays and must give the same
// answer whether it built it all at once or a version at a time; and reading a
// history that did not come from dt, which has to arrive at the same text dt
// itself would.
const fs = require('fs')
const vm = require('vm')
const path = require('path')
const DIR = __dirname
let passed = 0, failed = 0
function check(name, fn) {
try {
fn()
console.log(` ok ${name}`)
passed++
} catch (e) {
console.log(` FAIL ${name}\n ${e.message}`)
failed++
}
}
function eq(actual, expected, what) {
const a = JSON.stringify(actual), b = JSON.stringify(expected)
if (a !== b) throw new Error(`${what}: got ${a}, wanted ${b}`)
}
function ok(cond, what) {
if (!cond) throw new Error(what)
}
// ---------------------------------------------------------------- the stub
// Enough of a window for these scripts to load and for the history view to
// lay itself out. It records nothing about styling, only structure, so it
// cannot check what the page looks like, only what it builds.
function make_window() {
const by_id = {}
const told = []
const listening = {}
const said = []
const tag_count = s => (String(s).match(/<[a-zA-Z]/g) || []).length
function el(tag) {
const e = {
tagName: tag, children: [], dataset: {}, textContent: '', firstChild: null,
style: new Proxy({}, { get: (t, k) => t[k] ?? '', set: (t, k, v) => (t[k] = v, true) }),
_html: '',
get innerHTML() { return this._html },
set innerHTML(v) {
this._html = v
if (tag_count(v)) this.firstChild = el('div')
for (const m of String(v).matchAll(/id="([^"]+)"/g))
by_id[m[1]] = by_id[m[1]] || el('div')
},
append(...c) { this.children.push(...c) },
appendChild(c) { this.children.push(c); return c },
remove() {},
closest: () => null,
getBoundingClientRect: () => ({ x: 0, y: 0, top: 0, left: 0,
bottom: 600, right: 900, width: 900, height: 600 }),
// Text is measured as a fixed width per character, which is all
// the column arithmetic needs and is stable across machines.
get offsetWidth() { return 8 * this.textContent.length },
scrollTop: 0, scrollHeight: 600, clientHeight: 600, clientWidth: 900,
addEventListener() {}, checked: false, value: '',
}
return e
}
const document = {
createElement: el,
body: el('body'),
// Only elements the markup has actually declared, so that code which
// builds its own containers is exercised rather than handed one.
getElementById: id => by_id[id] || null,
// Kept, so a test can drive a whole press, move and release: the
// move and release listeners go on the document, not the window
addEventListener: (type, fn) => (listening[type] ??= []).push(fn),
}
const win = {
document, console,
requestAnimationFrame: f => f(),
// Kept, so a test can raise one the way the browser would
addEventListener: (type, fn) => (listening[type] ??= []).push(fn),
onload: null,
setTimeout, clearTimeout, setInterval, clearInterval, atob, btoa,
TextEncoder, TextDecoder, performance, AbortController, Blob,
crypto: require('crypto').webcrypto,
backgroundConnection: { postMessage() {} },
navigator: { userAgent: 'test' },
location: { href: 'about:blank' },
// Present, and without the Firefox marking that makes content-script.js
// put its own in place of it.
ReadableStream: class {},
chrome: {
runtime: {
getURL: f => path.join(DIR, f),
connect: () => ({ postMessage() {}, onMessage: { addListener() {} } }),
// Kept, so a test can deliver what the background would say
onMessage: { addListener: fn => told.push(fn) },
sendMessage: m => said.push(m),
},
devtools: { inspectedWindow: { tabId: 1 } },
},
}
win.getSelection = () => ({ toString: () => '' })
// Only inline styles exist here, so that is all this can report
win.getComputedStyle = e => e.style
win.window = win
win.self = win
win.globalThis = win
// The ids panel.js expects the markup to have provided
for (const id of ['id_messages', 'id_raw_messages', 'subscribe_response',
'encoding_response', 'version_response', 'parents_response',
'merge_type_response', 'content_type_response', 'error_d', 'error_d_label',
'edit_source_d', 'encoding_request', 'merge_type_select',
'content_type_select', 'subscribe_request', 'version_request',
'parents_request', 'edit_source', 'resubmit_button', 'show_resubmit',
'id_time_travel', 'id_time_travel_label',
'id_show_deletions', 'id_show_deletions_label'])
win[id] = by_id[id] = el('div')
return { win, by_id, told, listening, said, ctx: vm.createContext(win) }
}
function load(ctx, file) {
const src = fs.readFileSync(path.join(DIR, file), 'utf8')
new vm.Script(src, { filename: file }).runInContext(ctx)
}
// ------------------------------------------- dt.js, and its transformations
console.log('\ndt.js is a usable classic script')
const dt_src = fs.readFileSync(path.join(DIR, 'dt.js'), 'utf8')
check('compiles as a classic script, not only as a module', () => {
new vm.Script(dt_src, { filename: 'dt.js' })
})
check('no export statements survive', () => {
const left = dt_src.split('\n').filter(l => /^\s*export\b/.test(l))
ok(left.length === 0, `${left.length} export line(s) remain, first: ${left[0]}`)
})
check('no import.meta, which a classic script cannot parse', () => {
const code = dt_src.split('\n').filter(l => !/^\s*\/\//.test(l)).join('\n')
ok(!code.includes('import.meta'), 'import.meta is still present')
})
check('the wasm url goes through chrome.runtime.getURL', () => {
ok(dt_src.includes("chrome.runtime.getURL('dt_bg.wasm')"),
"expected chrome.runtime.getURL('dt_bg.wasm')")
})
check('dt_bg.wasm is present and is wasm', () => {
const b = fs.readFileSync(path.join(DIR, 'dt_bg.wasm'))
eq([...b.subarray(0, 4)], [0x00, 0x61, 0x73, 0x6d], 'wasm magic number')
})
// -------------------------------------------------- the engine, once loaded
console.log('\nthe engine loads and answers')
const engine = make_window()
let engine_ready = false
check('dt.js and dt-helpers.js load together', () => {
load(engine.ctx, 'dt.js')
load(engine.ctx, 'dt-helpers.js')
for (const name of ['initSync', 'Doc', 'dt_diff_from', 'encode_version', 'decode_version'])
ok(vm.runInContext(`typeof ${name}`, engine.ctx) !== 'undefined',
`${name} is not defined`)
})
check('the wasm initializes', () => {
const w = fs.readFileSync(path.join(DIR, 'dt_bg.wasm'))
engine.ctx.__wasm = w.buffer.slice(w.byteOffset, w.byteOffset + w.byteLength)
vm.runInContext('initSync({ module: __wasm })', engine.ctx)
engine_ready = true
})
const run = js => vm.runInContext(js, engine.ctx)
check('a document edits and reads back', () => {
ok(engine_ready, 'the wasm did not initialize')
eq(run(`(() => { let d = new Doc('a'); d.ins(0, 'hello'); d.ins(5, ' world');
d.del(0, 1); d.ins(0, 'H'); return d.get() })()`),
'Hello world', 'document text')
})
check('getUpdates returns braid updates', () => {
const u = run(`(() => { let d = new Doc('alice'); d.ins(0, 'hello');
return d.getUpdates(null) })()`)
eq(u.length, 1, 'one run summarized into one update')
eq(u[0].version, ['alice-4'], 'version names the run\'s last event')
eq(u[0].first_event, 'alice-0', 'first_event names the run\'s first')
eq(u[0].parents, [], 'no parents')
eq(u[0].patches, [{ unit: 'text', range: '[0:0]', content: 'hello' }], 'one range patch')
})
check('a forward delete emits one update per character', () => {
// Each event deletes whatever now sits at the same position, so the runs
// cannot be summarized and every one addresses the same one-character span.
const u = run(`(() => { let d = new Doc('a'); d.ins(0, 'abcdef'); d.del(1, 3);
return d.getUpdates(['a-5']) })()`)
eq(u.length, 3, 'one update per deleted character')
eq(u.map(x => x.patches[0].range), ['[1:2]', '[1:2]', '[1:2]'], 'delete ranges')
eq(u.map(x => x.patches[0].content), ['', '', ''], 'a delete carries no content')
})
check('numLocalVersions counts events, not updates', () => {
eq(run(`(() => { let d = new Doc('a'); d.ins(0, 'hello');
return [d.numLocalVersions(), d.getUpdates(null).length] })()`),
[5, 1], '[events, updates]')
})
check('getUpdatesInSpan covers a window of history', () => {
const r = run(`(() => {
let d = new Doc('a')
for (let i = 0; i < 10; i++) d.ins(0, 'x')
let n = d.numLocalVersions()
let half = Math.floor(n / 2)
let a = d.getUpdatesInSpan(0, half), b = d.getUpdatesInSpan(half, n)
let count = us => us.reduce((t, u) => t + [...u.patches[0].content].length, 0)
return [n, count(a) + count(b), d.getUpdatesInSpan(0, 0).length]
})()`)
eq(r[0], r[1], 'adjacent spans cover every event exactly once')
eq(r[2], 0, 'an empty span is empty')
})
check('a document round-trips through bytes', () => {
const r = run(`(() => {
let a = new Doc('a'); a.ins(0, 'hello there')
let b = new Doc('b'); b.mergeBytes(a.toBytes())
return [a.get() === b.get(), b.getUpdates(null).length === a.getUpdates(null).length]
})()`)
eq(r, [true, true], '[same text, same updates]')
})
check('concurrent edits merge the same way on both sides', () => {
const r = run(`(() => {
let a = new Doc('a'); a.ins(0, 'hello')
let b = new Doc('b'); b.mergeBytes(a.toBytes())
a.ins(5, ' from a'); b.ins(0, 'B says: ')
let a2 = a.toBytes(), b2 = b.toBytes()
a.mergeBytes(b2); b.mergeBytes(a2)
return [a.get(), b.get()]
})()`)
eq(r[0], r[1], 'both peers converge on the same text')
})
check('encode_version and decode_version are inverses', () => {
eq(run(`decode_version(encode_version('agent', 7))`), ['agent', 7], 'round trip')
// An agent name may contain a hyphen, so only the last one separates
eq(run(`decode_version(encode_version('a-weird-name', 12))`),
['a-weird-name', 12], 'hyphenated agent name')
})
// ------------------------------- the windowed diff against the simple one
console.log('\nmarking up a window says what marking up everything says')
// diff_from_ops used to take the whole document apart, a heap object per
// character, to mark up the line a version touched. It now works on just the
// stretch the operations reach. The version it replaced is kept here as the
// spec -- frozen, because reading it out of dt-helpers.js would make the
// oracle track the very file under test, and then breaking one would break
// both and nothing would ever be reported.
run(`function reference_diff_from_ops(text, ops) {
let a = [...text].map(c => ({ c, ins: null, gone: null }))
let far_left = []
for (let xf of ops) {
if (xf.kind == "Ins") {
let tail = a.splice(xf.start, a.length - xf.start)
for (let c of xf.content) a.push({ c, ins: xf.agent, gone: null })
for (let cell of tail) a.push(cell)
} else if (xf.kind == "Del") {
let removed = a.splice(xf.start, xf.end - xf.start)
let text = removed.map(x => x.c + (x.gone || []).map(g => g[0]).join('')).join('')
if (!text) continue
if (xf.start == 0) far_left.push([text, xf.agent])
else {
let prev = a[xf.start - 1]
if (!prev.gone) prev.gone = []
prev.gone.push([text, xf.agent])
}
}
}
let diff = []
let push = (what, text, agent) => {
if (!text) return
let last = diff[diff.length - 1]
if (last && last[0] === what && last[2] === agent) last[1] += text
else diff.push([what, text, agent])
}
for (let [text, agent] of far_left) push(-1, text, agent)
for (let cell of a) {
push(cell.ins ? 1 : 0, cell.c, cell.ins)
for (let [text, agent] of cell.gone || []) push(-1, text, agent)
}
return diff
}`)
// Deterministic, so a failure can be replayed from its seed
run(`
var __seed = 20260809
function __rnd() { __seed = (__seed * 1103515245 + 12345) & 0x7fffffff
return __seed / 0x7fffffff }
// Astral characters on purpose: dt counts code points, JS strings index
// utf-16 units, and the gap between them is where a window goes wrong
var __AL = ['a','b',' ','\\n','x','.','\u00e9','\ud83d\ude42','\u4e2d','\\t']
function __blob(n) { var s = ''
for (var i = 0; i < n; i++) s += __AL[Math.floor(__rnd() * __AL.length)]
return s }
// Concurrency comes from separate documents merging, which is the only way
// to get histories shaped like the ones a real session produces
function __history(agents, edits) {
var docs = []
for (var i = 0; i < agents; i++) docs.push(new Doc('agent' + i))
var marks = []
for (var e = 0; e < edits; e++) {
var who = Math.floor(__rnd() * agents), what = __rnd(), r = __rnd()
var d = docs[who], L = [...d.get()].length
if (what < 0.62) d.ins(Math.floor(r * (L + 1)), __blob(1 + Math.floor(r * 12)))
else if (what < 0.85 && L > 0) {
var p = Math.floor(r * L)
d.del(p, Math.min(1 + Math.floor(r * 6), L - p))
} else {
var o = docs[(who + 1) % agents]
d.mergeBytes(o.toBytes()); o.mergeBytes(d.toBytes())
}
if (e % 3 === 0) marks.push(docs[0].getRemoteVersion().map(x => x.join('-')).sort())
}
for (var i = 1; i < agents; i++) docs[0].mergeBytes(docs[i].toBytes())
marks.push(docs[0].getRemoteVersion().map(x => x.join('-')).sort())
return { doc: docs[0], marks }
}
// Every span of a history, both the wide ones and the narrow ones a
// time-travel scroll actually asks for
function __disagreements(agents, edits) {
var h = __history(agents, edits), bad = []
for (var i = 0; i < h.marks.length; i++) {
for (var j = i; j < h.marks.length; j += Math.max(1, (h.marks.length / 9) | 0))
bad.push(__compare(h, i, j))
for (var j = i; j < Math.min(h.marks.length, i + 3); j++)
bad.push(__compare(h, i, j))
}
return bad.filter(Boolean)
}
function __compare(h, i, j) {
var lv = h.doc.remoteToLocalVersion(h.marks[i])
var text = h.doc.getStringAt(lv)
var ops = i === j ? h.doc.xfSince(lv)
: h.doc.xfBetween(lv, h.doc.remoteToLocalVersion(h.marks[j]))
var want = JSON.stringify(reference_diff_from_ops(text, ops))
var got = JSON.stringify(diff_from_ops(text, ops))
return want === got ? null : { i, j, ops: ops.length, want: want.slice(0, 200),
got: got.slice(0, 200) }
}
`)
for (const [agents, edits] of [[1, 60], [2, 90], [3, 120], [5, 180]]) {
check(`${agents} writer(s), ${edits} edits: every span agrees`, () => {
const bad = run(`__disagreements(${agents}, ${edits})`)
eq(bad.length, 0, `disagreed on ${bad.length} span(s), first: ${JSON.stringify(bad[0])}`)
})
}
// dt's own histories never produced some of these -- across four generated
// histories, not one deletion ever landed at position 0, which is its own
// branch and exactly the sort a window gets wrong.
const BY_HAND = [
['a deletion at the very start', 'hello world', [{ kind: 'Del', agent: 'a', start: 0, end: 5 }]],
['deleting everything there is', 'hello', [{ kind: 'Del', agent: 'a', start: 0, end: 5 }]],
['delete at the start, then fill', 'hello', [{ kind: 'Del', agent: 'a', start: 0, end: 2 },
{ kind: 'Ins', agent: 'b', start: 0, content: 'XY' }]],
['deleting what this span wrote', 'abc', [{ kind: 'Ins', agent: 'a', start: 1, content: 'ZZ' },
{ kind: 'Del', agent: 'b', start: 1, end: 3 }]],
['a delete straddling both', 'abcde', [{ kind: 'Ins', agent: 'a', start: 1, content: 'X' },
{ kind: 'Del', agent: 'b', start: 1, end: 3 }]],
['two deletions meeting', 'abcdef', [{ kind: 'Del', agent: 'a', start: 2, end: 4 },
{ kind: 'Del', agent: 'a', start: 1, end: 2 }]],
['deletions by different hands', 'abcdef', [{ kind: 'Del', agent: 'a', start: 1, end: 3 },
{ kind: 'Del', agent: 'b', start: 1, end: 2 }]],
['ops at both ends at once', 'abcdefghij', [{ kind: 'Del', agent: 'a', start: 0, end: 1 },
{ kind: 'Ins', agent: 'b', start: 8, content: 'Z' }]],
['an insert at the very end', 'abc', [{ kind: 'Ins', agent: 'a', start: 3, content: 'd' }]],
['an insert into nothing', '', [{ kind: 'Ins', agent: 'a', start: 0, content: 'new' }]],
['no operations at all', 'abc', []],
['an insert of nothing', 'abc', [{ kind: 'Ins', agent: 'a', start: 1, content: '' }]],
['a pair deleted whole', 'a\u{1F642}b', [{ kind: 'Del', agent: 'a', start: 1, end: 2 }]],
['a pair inserted mid-string', 'ab', [{ kind: 'Ins', agent: 'a', start: 1, content: '\u{1F642}\u{4E2D}' }]],
['a pair at position zero', '\u{1F642}ab', [{ kind: 'Del', agent: 'a', start: 0, end: 1 }]],
['a family of joined code points', 'x\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F466}y',
[{ kind: 'Del', agent: 'a', start: 1, end: 2 }]],
]
for (const [name, text, ops] of BY_HAND) {
check(`by hand: ${name}`, () => {
engine.ctx.__t = text, engine.ctx.__o = ops
eq(run('diff_from_ops(__t, __o)'), run('reference_diff_from_ops(__t, __o)'), 'the runs')
})
}
check('one span shown this way is the span shown the old way', () => {
// dt_diff_spans has to be a strict generalisation, or every single-span
// view in the panel quietly changes meaning
const bad = run(`(() => {
var h = __history(3, 120), bad = []
for (var i = 0; i < h.marks.length - 1; i++) {
var to = h.marks[Math.min(h.marks.length - 1, i + 1 + (i % 5))]
var one = JSON.stringify(dt_diff_spans(h.doc,
[{ from_version: h.marks[i], to_version: to }]))
var old = JSON.stringify(dt_diff_from(h.doc, h.marks[i], to))
if (one !== old) bad.push(i)
}
return bad
})()`)
eq(bad.length, 0, `disagreed on ${bad.length} span(s), first at mark ${bad[0]}`)
})
check('two spans that meet say what the one span covering both says', () => {
const bad = run(`(() => {
var h = __history(3, 120), bad = []
for (var i = 0; i + 8 < h.marks.length; i += 3) {
var a = h.marks[i], mid = h.marks[i + 3], b = h.marks[i + 6]
var split = JSON.stringify(dt_diff_spans(h.doc,
[{ from_version: a, to_version: mid },
{ from_version: mid, to_version: b }]))
var whole = JSON.stringify(dt_diff_spans(h.doc,
[{ from_version: a, to_version: b }]))
if (split !== whole) bad.push(i)
}
return bad
})()`)
eq(bad.length, 0, `disagreed at ${bad.length} place(s), first at mark ${bad[0]}`)
})
check('what is left after the strikings is the document itself', () => {
// The strong one. Spans with gaps between them only line up if the changes
// in the gaps are applied too -- drop those and everything after them sits
// at the wrong place, and this text stops matching.
const bad = run(`(() => {
var h = __history(3, 150), bad = []
for (var i = 0; i + 12 < h.marks.length; i += 4) {
var spans = [{ from_version: h.marks[i], to_version: h.marks[i + 2] },
{ from_version: h.marks[i + 6], to_version: h.marks[i + 8] },
{ from_version: h.marks[i + 10], to_version: h.marks[i + 12] }]
var shown = dt_diff_spans(h.doc, spans)
.filter(r => r[0] !== -1).map(r => r[1]).join('')
var real = h.doc.getStringAt(h.doc.remoteToLocalVersion(h.marks[i + 12]))
if (shown !== real) bad.push({ i, shown: shown.slice(0, 60), real: real.slice(0, 60) })
}
return bad
})()`)
eq(bad.length, 0, `wrong text at ${bad.length} place(s): ${JSON.stringify(bad[0])}`)
})
check('a gap is applied but never called out', () => {
// alice writes, bob writes in the gap, alice writes again
const marks = run(`(() => {
var d = new Doc('alice'); d.ins(0, 'one ')
var v0 = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(4, 'ALICE ')
var v1 = d.getRemoteVersion().map(x => x.join('-')).sort()
var b = new Doc('bob'); b.mergeBytes(d.toBytes()); b.ins(10, 'BOB ')
d.mergeBytes(b.toBytes())
var v2 = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(d.get().length, 'END')
var v3 = d.getRemoteVersion().map(x => x.join('-')).sort()
__d = d
return [v0, v1, v2, v3]
})()`)
engine.ctx.__spans = [{ from_version: marks[0], to_version: marks[1] },
{ from_version: marks[2], to_version: marks[3] }]
const diff = run('dt_diff_spans(__d, __spans)')
const by = w => diff.filter(r => r[0] === w).map(r => r[1]).join('')
eq(by(1), 'ALICE END', "what the selected spans wrote")
ok(by(0).includes('BOB '), `the gap's text is missing entirely: ${JSON.stringify(by(0))}`)
eq(diff.filter(r => r[0] === 1 && r[2] === 'bob').length, 0,
'the gap was called out as though it had been selected')
})
check('a gap that deletes still leaves the writing it took away on screen', () => {
// Otherwise selecting the span that wrote something, but not the one that
// removed it, shows no sign the writing ever happened
const marks = run(`(() => {
var d = new Doc('alice'); d.ins(0, 'keep ')
var v0 = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(5, 'ALICEWROTE ') // selected
var v1 = d.getRemoteVersion().map(x => x.join('-')).sort()
var b = new Doc('bob'); b.mergeBytes(d.toBytes())
b.del(5, 11) // the gap takes it away
d.mergeBytes(b.toBytes())
var v2 = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(d.get().length, 'END') // selected
var v3 = d.getRemoteVersion().map(x => x.join('-')).sort()
__d2 = d
return [v0, v1, v2, v3]
})()`)
engine.ctx.__s2 = [{ from_version: marks[0], to_version: marks[1] },
{ from_version: marks[2], to_version: marks[3] }]
const diff = run('dt_diff_spans(__d2, __s2)')
const struck = diff.filter(r => r[0] === -1)
eq(struck.map(r => r[1]).join(''), 'ALICEWROTE ', 'what is shown struck through')
eq(struck.map(r => r[2]), ['alice'],
'struck in the wrong hand: it should be whoever wrote it, not who removed it')
eq(diff.filter(r => r[0] !== -1).map(r => r[1]).join(''), 'keep END',
'the document itself')
})
check('spans on branches that never met still line up', () => {
// Asking across two concurrent frontiers lands on their merge, so the
// running point has to take that in. Replacing it instead re-applies what
// has already been applied, and the text comes out doubled.
const out = run(`(() => {
var a = new Doc('alice'); a.ins(0, 'base ')
var forked = a.getRemoteVersion().map(x => x.join('-')).sort()
var b = new Doc('bob'); b.mergeBytes(a.toBytes())
a.ins(5, 'ALICE ')
var a_tip = a.getRemoteVersion().map(x => x.join('-')).sort()
b.ins(5, 'BOB ')
var b_tip = b.getRemoteVersion().map(x => x.join('-')).sort()
a.mergeBytes(b.toBytes())
var merged = a.getRemoteVersion().map(x => x.join('-')).sort()
var diff = dt_diff_spans(a, [{ from_version: forked, to_version: a_tip },
{ from_version: forked, to_version: b_tip }])
return { shown: diff.filter(r => r[0] !== -1).map(r => r[1]).join(''),
real: a.getStringAt(a.remoteToLocalVersion(merged)),
marked: diff.filter(r => r[0] === 1).map(r => [r[1], r[2]]) }
})()`)
eq(out.shown, out.real, 'the text shown is not the document the two branches make')
eq(out.marked.map(m => m[1]).sort(), ['alice', 'bob'], 'both branches called out')
})
check('a span after a concurrent one is placed against both branches', () => {
// The running point has to take in every branch selected so far. Replacing
// it with the last span's end drops the others, and the stretch after it
// hands back work already applied -- which shows up as doubled text.
const out = run(`(() => {
var d = new Doc('alice'); d.ins(0, 'base ')
var v0 = d.getRemoteVersion().map(x => x.join('-')).sort()
var b = new Doc('bob'); b.mergeBytes(d.toBytes())
d.ins(5, 'A1 ')
var v1 = d.getRemoteVersion().map(x => x.join('-')).sort()
b.ins(5, 'B1 ')
var vb = b.getRemoteVersion().map(x => x.join('-')).sort()
d.mergeBytes(b.toBytes())
var vm = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(d.get().length, 'A2')
var v2 = d.getRemoteVersion().map(x => x.join('-')).sort()
var diff = dt_diff_spans(d, [{ from_version: v0, to_version: v1 },
{ from_version: v0, to_version: vb },
{ from_version: vm, to_version: v2 }])
return { shown: diff.filter(r => r[0] !== -1).map(r => r[1]).join(''),
real: d.getStringAt(d.remoteToLocalVersion(v2)) }
})()`)
eq(out.shown, out.real, 'the text shown is not the document those spans make')
eq((out.shown.match(/A1/g) || []).length, 1, 'a branch was applied twice over')
})
// ------------------------------------- keeping the reader's place across views
console.log('\nkeeping the place the reader was looking at')
check('a place in unchanged text means the same place in the document', () => {
// runs: "keep " kept, "NEW" added, " rest" kept
const runs = [[0, 'keep ', null], [1, 'NEW', 'alice'], [0, ' rest', null]]
engine.ctx.__r = runs
eq(run('shown_to_document(__r, 0, true)'), 0, 'the very start')
eq(run('shown_to_document(__r, 3, true)'), 3, 'inside the kept text')
eq(run('shown_to_document(__r, 7, true)'), 7, 'inside the added text')
eq(run('shown_to_document(__r, 10, true)'), 10, 'after it')
})
check('struck text is on the screen but not in the document', () => {
// "keep " kept, "GONE" struck out, " rest" kept
engine.ctx.__r = [[0, 'keep ', null], [-1, 'GONE', 'bob'], [0, ' rest', null]]
eq(run('shown_to_document(__r, 5, true)'), 5, 'where the struck text begins')
// Reading inside text that is gone: the place it was taken from
eq(run('shown_to_document(__r, 7, true)'), 5, 'inside the struck text')
eq(run('shown_to_document(__r, 9, true)'), 5, 'just past it')
eq(run('shown_to_document(__r, 11, true)'), 7, 'two into the text after it')
})
check('and it is not on the screen at all with deletions turned off', () => {
engine.ctx.__r = [[0, 'keep ', null], [-1, 'GONE', 'bob'], [0, ' rest', null]]
// The struck run is never drawn, so it takes up none of what is shown
eq(run('shown_to_document(__r, 6, false)'), 6, 'one into the text after it')
})
check('astral characters count as one place, not two', () => {
// The documents count code points; a JS string counts utf-16 units
engine.ctx.__r = [[0, 'a\u{1F642}b', null], [1, 'X', 'alice']]
eq(run('shown_to_document(__r, 3, true)'), 3, 'past the pair')
eq(run('cp_to_units("a\u{1F642}b", 2)'), 3, 'a code-point offset, in utf-16 units')
eq(run('cp_to_units("abc", 2)'), 2, 'nothing to do without a pair')
})
check('a place moves along as the document is written into', () => {
const out = run(`(() => {
var d = new Doc('alice'); d.ins(0, 'one two three')
var v = d.getRemoteVersion().map(x => x.join('-')).sort()
d.ins(0, 'START ') // 6 written before the place
d.ins(d.get().length, ' END') // and some after it, which moves nothing
return { at: xf_position(d, v, 4), text: d.get() }
})()`)
eq(out.at, 10, 'the place was not carried along by the writing before it')
eq(out.text.slice(10, 13), 'two', 'and it is not on the same word')
})
check('and back again as text before it is taken away', () => {
eq(run(`(() => {
var d = new Doc('alice'); d.ins(0, 'one two three')
var v = d.getRemoteVersion().map(x => x.join('-')).sort()
d.del(0, 4) // "one " goes
return xf_position(d, v, 4)
})()`), 0, 'the place did not come back with the text')
})
check('a place swallowed by a deletion lands at the near edge of the hole', () => {
eq(run(`(() => {
var d = new Doc('alice'); d.ins(0, 'one two three')
var v = d.getRemoteVersion().map(x => x.join('-')).sort()
d.del(2, 8) // the place at 4 is inside this
return xf_position(d, v, 4)
})()`), 2, 'the place did not fall back to the edge')
})
check('nothing written since leaves the place where it was', () => {
eq(run(`(() => {
var d = new Doc('alice'); d.ins(0, 'one two three')
var v = d.getRemoteVersion().map(x => x.join('-')).sort()
return xf_position(d, v, 7)
})()`), 7, 'a place moved for no reason')
})
check('the two halves carry a place from the diff to the document now', () => {
// The whole journey: halfway down a diff, out through what it is showing,
// and on into the document the editor is about to put back on screen
const out = run(`(() => {
var d = new Doc('alice'); d.ins(0, 'alpha bravo charlie delta')
var from = d.getRemoteVersion().map(x => x.join('-')).sort()
d.del(6, 6) // "bravo " goes -- del takes a length
var to = d.getRemoteVersion().map(x => x.join('-')).sort()
var runs = dt_diff_from(d, from, to)
d.ins(0, 'ZERO ') // and the world moves on
// reading at "charlie" in the diff, which still shows "bravo " struck
var shown = d.getStringAt(d.remoteToLocalVersion(from))
var at_charlie_on_screen = shown.indexOf('charlie')
var at = shown_to_document(runs, at_charlie_on_screen, true)
return { doc_at_to: at, now: xf_position(d, to, at), text: d.get() }
})()`)
eq(out.doc_at_to, 6, 'in the document the span ends at')
eq(out.text.slice(out.now, out.now + 7), 'charlie', 'the reader lost the word')
})
check('a window is only opened as far as the operations reach', () => {
// The whole point: one edit in a long document should not take the
// document apart to mark it up
// An insert sits between two characters and takes none of them apart:
// what it adds comes from the operation, not from the text
eq(run(`touched_range(1000, [{kind:'Ins', agent:'a', start:400, content:'hi'}])`),
[400, 400], 'an insert in the middle')
// The ten characters going away have to be inside the window to be taken
// out of it, and the one before them is written on with what they held
eq(run(`touched_range(1000, [{kind:'Del', agent:'a', start:400, end:410}])`),
[399, 410], 'a delete in the middle, plus the cell it writes on')
eq(run(`touched_range(1000, [{kind:'Ins', agent:'a', start:1000, content:'x'}])`),
[1000, 1000], 'an append reaches nothing at all')
eq(run(`touched_range(1000, [])`), [0, 0], 'no operations')
})
check('but operations at both ends open it all the way', () => {
// A single window has to span them, which is the shape that gains least
// 989, not 990: the second insert is addressed against the text the first
// one left, which is a character longer
eq(run(`touched_range(1000, [{kind:'Ins', agent:'a', start:5, content:'x'},
{kind:'Ins', agent:'b', start:990, content:'y'}])`),
[5, 989], 'a window reaching both')
})
// -------------------------------------------------- the history view layout
console.log('\nthe history view lays out and virtualizes')
const panel = make_window()
check('panel.js loads', () => {
load(panel.ctx, 'dt.js')
load(panel.ctx, 'dt-helpers.js')
load(panel.ctx, 'panel.js')
ok(typeof panel.ctx.layout_history === 'function', 'layout_history is not defined')
ok(typeof panel.ctx.render_history_window === 'function',
'render_history_window is not defined')
})
// A long single-author run, with one fork partway through, plus one version
// whose content wraps over several lines.
const versions = []
for (let i = 0; i < 4000; i++) {
let parents = i === 0 ? [] : [`alice-${i - 1}`]
if (i === 2000) parents = ['alice-1998', 'bob-0']
versions.push({ method: 'GET', version: [`alice-${i}`], parents,
patches: [{ unit: 'text', range: `${i}:${i}`, content: 'x' }] })
}
versions[3].patches = [{ unit: 'text', range: '3:3',
content: 'first line\nsecond line\n' + 'z'.repeat(400) }]
versions.splice(1999, 0, { method: 'GET', version: ['bob-0'], parents: ['alice-1997'],
patches: [{ unit: 'text', range: '5:9', content: '' }] })
panel.ctx.__vs = versions
const prun = js => vm.runInContext(js, panel.ctx)
prun(`function fill(n) { versions.length = 0; for (let i = 0; i < n; i++) versions.push(__vs[i]) }
function append(a, b) { for (let i = a; i < b; i++) versions.push(__vs[i]) }
function snapshot() {
return JSON.stringify({ rows: layout.rows.length, height: layout.height,
tops: layout.row_tops, circles: layout.circles, edges: layout.edges })
}`)
const N = versions.length
check('it renders only the rows in the viewport', () => {
prun(`fill(${N}); layout = null; layout_history(); render_history_window()`)
const rows = panel.by_id['history_rows'].innerHTML
const drawn = (rows.match(/data-vi=/g) || []).length
ok(drawn > 0, 'nothing was drawn')
ok(drawn < 150, `${drawn} rows drawn for ${N} versions, so it is not virtualizing`)
})
check('scrolling draws a different set of rows', () => {
const first = panel.by_id['history_rows'].innerHTML
panel.win.id_messages.scrollTop = 20000
prun('render_history_window()')
const later = panel.by_id['history_rows'].innerHTML
ok(first !== later, 'the same rows were drawn after scrolling')
panel.win.id_messages.scrollTop = 0
})
check('appending gives the same layout as building it all at once', () => {
prun(`fill(${N}); layout = null; layout_history()`)
const all_at_once = prun('snapshot()')
prun(`fill(${N - 500}); layout = null; layout_history()`)
prun(`append(${N - 500}, ${N}); layout_history()`)
ok(prun('snapshot()') === all_at_once, 'a batch of 500 diverged from a full rebuild')
prun(`fill(${N - 20}); layout = null; layout_history()`)
for (let i = N - 20; i < N; i++) prun(`append(${i}, ${i + 1}); layout_history()`)
ok(prun('snapshot()') === all_at_once, 'one at a time diverged from a full rebuild')
})
check('content wrapping makes a row taller, and moves the rows below it', () => {
prun(`fill(${N}); layout = null; layout_history(); render_history_window()`)
const rows = panel.by_id['history_rows'].innerHTML.split('<div data-vi=').slice(1)
const tall = rows.find(r => r.includes('second line'))
ok(tall, 'the multi-line version was not drawn')
const height = +tall.match(/height:(\d+)px/)[1]
const tops = rows.map(r => +(r.match(/top:(\d+)px/) || [0, 0])[1])
ok(height > 100, `the wrapping row is only ${height}px tall`)
ok(tall.includes('pre-wrap') && tall.includes('break-all'),
'content is not set to wrap at the column edge')
ok(tall.includes('first line\nsecond line'), 'newlines were not kept')
for (let i = 1; i < tops.length; i++)
ok(tops[i] > tops[i - 1], 'rows are not in increasing order down the page')
})
// ------------------------------------------------ selecting a span of time
console.log('\nselecting a span of time')
check('a span of one version is the degenerate case of a drag', () => {
prun('span = null; select_span(7, 7)')
eq(prun('[layout.vs[Math.min(span.a, span.b)].version[0], span.a === span.b]'),
['alice-7', true], '[version, single]')
})
check('rows carry no click handler, so their text can be selected', () => {
prun(`fill(${N}); layout = null; layout_history(); render_history_window()`)
const rows = panel.by_id['history_rows'].innerHTML
ok(!rows.includes('cursor:pointer'), 'rows still look clickable')
ok(!rows.includes('onclick'), 'rows still carry a click handler')
})
check('the band covers the version DAG and the identifiers beside it', () => {
prun(`fill(${N}); layout = null; layout_history(); select_span(2, 6, true)`)
const g = panel.by_id['history_gutter']
ok(panel.by_id['history_band'].innerHTML.includes('background:rgba'),
'no highlighter drawn')
ok(g.innerHTML.includes('data-grip="body"'), 'no grips drawn')
ok(g.innerHTML.includes('data-grip="top"') && g.innerHTML.includes('data-grip="bottom"'),
'the two edge handles are missing')
// The band fills the gutter, and the gutter reaches past the DAG to cover
// the identifiers, which is also the region you can drag a span out of.
const w = parseInt(g.style.width)
ok(w === prun('layout.band_w'), `gutter is ${w}px, layout says ${prun('layout.band_w')}`)
ok(w > prun('DAG_W'), `the gutter stops at the DAG (${w}px)`)
ok(w <= prun('DAG_W + layout.cols.version'),
'the gutter reaches past the identifiers into blank space')
})
check('the band spans exactly the selected versions', () => {
prun('select_span(2, 6, true)')
const band = panel.by_id['history_band'].innerHTML.match(/top:(\d+)px;\s*height:(\d+)px/)
ok(band, 'could not read the band geometry')
const [top, height] = [+band[1], +band[2]]
eq([top, top + height],
[prun('version_top(2)'), prun('version_bottom(6)')], '[band top, band bottom]')
})
check('a span selected backwards covers the same versions', () => {
prun('select_span(6, 2)')
const a = panel.by_id['history_band'].innerHTML.match(/top:(\d+)px;\s*height:(\d+)px/)
prun('select_span(2, 6)')
const b = panel.by_id['history_band'].innerHTML.match(/top:(\d+)px;\s*height:(\d+)px/)
eq([a[1], a[2]], [b[1], b[2]], 'dragging up and dragging down')
})
check('a point on the page maps back to the version drawn there', () => {
for (const vi of [0, 3, 50, 1999, 2500]) {
const top = prun(`version_top(${vi})`), bot = prun(`version_bottom(${vi})`)
eq(prun(`version_at(${(top + bot) / 2})`), vi, `middle of version ${vi}`)
eq(prun(`version_at(${top})`), vi, `top edge of version ${vi}`)
}
})
check('the cursor keeps its meaning while a span is being drawn', () => {
prun('select_span(2, 6)')
prun(`drag = { mode: 'edge', cursor: 'ns-resize', anchor: 2, y: 0 }`)
prun('render_history_window()')
const g = panel.by_id['history_gutter']
eq(g.style.cursor, 'ns-resize', 'gutter cursor while drawing a span')
ok(!/cursor:(grab|ns-resize)"/.test(g.innerHTML),
'a grip talks over the cursor of the drag in progress')
prun('drag = null; render_history_window()')
})
check('pressing on a span closes the hand before any movement', () => {
prun('select_span(2, 6)')
const g = panel.by_id['history_gutter']
eq(g.style.cursor, 'ns-resize', 'before the press')
ok(g.innerHTML.includes('cursor:grab'), 'the span should offer a hand to take')
// press on the body, with no mousemove following
const top = prun('version_top(2)')
panel.by_id['history_gutter'].onmousedown({
clientY: top + 4, preventDefault() {}, target: { dataset: { grip: 'body' } },
})
eq(g.style.cursor, 'grabbing', 'the hand did not close on mousedown')
ok(!g.innerHTML.includes('cursor:grab'), 'a grip still offers the open hand')
prun('drag = null; document.body.style.cursor = ""; render_history_window()')
})
check('the cursor of a finished drag does not stay on screen', () => {
prun('select_span(2, 6)')
// slide the whole span, which is the one gesture that closes the hand
prun(`drag = { mode: 'move', cursor: 'grabbing', from: 4, y: 0, a: 2, b: 6 }`)
prun('render_history_window()')
eq(panel.by_id['history_gutter'].style.cursor, 'grabbing', 'mid-drag')
prun('drag = null; render_history_window()')
const g = panel.by_id['history_gutter']
eq(g.style.cursor, 'ns-resize', 'after the drag ends')
ok(g.innerHTML.includes('cursor:grab'), 'the span offers no hand once released')
ok(!g.innerHTML.includes('cursor:inherit'), 'grips still deferring to a dead drag')
})
check('the cursors say what each part of the band does', () => {
prun('select_span(2, 6, true)')
const g = panel.by_id['history_gutter']
// Drawing a span, and moving either edge, is the window-border gesture.
// The hand is kept for sliding a whole span, which really is picking
// something up.
prun('select_span(null, null); render_history_window()')
eq(panel.by_id['history_gutter'].style.cursor, 'ns-resize', 'empty gutter cursor')
prun('select_span(2, 6); render_history_window()')
ok(panel.by_id['history_gutter'].innerHTML.includes('cursor:grab'),
'a selected span offers no hand to move it')
ok(g.innerHTML.includes('cursor:grab'), 'the band body is not grabbable')
ok((g.innerHTML.match(/cursor:ns-resize/g) || []).length === 2,
'both edges should resize')
})
// --------------------------------------------------------- time travel line
console.log('\ntime travelling with the scroll')
// A stand-in for the panel's own copy of the document, which the real panel
// builds from the history the page sends it.
prun(`dt_doc = { getStringAt: lv => 'text@' + lv, remoteToLocalVersion: v => v[0] }`)
prun('__doc = dt_doc')
check('the line stays hidden until it is switched on', () => {
prun('select_span(null, null)')
panel.win.id_time_travel.checked = false
prun('update_time_travel()')
eq(panel.by_id['history_line'].style.display, 'none', 'line display')
})
check('switching it on puts the line across the middle of the view', () => {
panel.win.id_time_travel.checked = true
prun('update_history_controls()')
panel.win.id_messages.scrollTop = 4000
prun('update_time_travel()')
eq(panel.by_id['history_line'].style.display, 'block', 'line display')
eq(panel.by_id['history_line'].style.top,
(4000 + panel.win.id_messages.clientHeight / 2) + 'px', 'line position')
})
check('the version under the line is the one being shown', () => {
panel.win.id_messages.scrollTop = 4000
prun('update_time_travel()')
const mid = 4000 + panel.win.id_messages.clientHeight / 2
const vi = prun(`version_at(${mid})`)
eq(prun('travelling_vi'), vi, 'version under the line')
eq(prun('[Math.min(span.a, span.b), Math.max(span.a, span.b)]'), [vi, vi],
'the span should be the single version under the line')
})
check('scrolling moves to a different version', () => {
panel.win.id_messages.scrollTop = 4000
prun('update_time_travel()')
const before = prun('travelling_vi')
panel.win.id_messages.scrollTop = 30000
prun('update_time_travel()')
ok(prun('travelling_vi') !== before, 'the same version after scrolling 26,000px')
})
check('raw messages turns time travel off', () => {
panel.win.id_raw_messages.checked = true
prun('update_time_travel()')
eq(panel.by_id['history_line'].style.display, 'none', 'line display')
eq(prun('travelling_vi'), null, 'the line is still following a version')
panel.win.id_raw_messages.checked = false
panel.win.id_time_travel.checked = false
})
check('raw messages lets go of the span and greys what acts on one', () => {
prun('select_span(10, 20)')
panel.win.id_raw_messages.checked = true
prun('update_history_controls()')
eq(prun('span'), null, 'a span nobody can see or adjust')
for (const box of ['id_time_travel', 'id_show_deletions'])
ok(panel.win[box].disabled, `${box} is still live`)
eq(panel.win.id_show_deletions_label.style.opacity, 0.4, 'the label still reads as live')
panel.win.id_raw_messages.checked = false
prun('update_history_controls()')
for (const box of ['id_time_travel', 'id_show_deletions'])
ok(!panel.win[box].disabled, `${box} stayed grey`)
})
check('placing a span by hand takes the job off the line', () => {
panel.win.id_time_travel.checked = true
prun('travelling_vi = null; update_time_travel()')
ok(prun('span') !== null, 'the line should have placed a span')
prun('select_span(10, 20)')
eq([panel.win.id_time_travel.checked, panel.win.id_time_travel.disabled],
[false, false], '[checked, disabled]')
eq(prun('[span.a, span.b]'), [10, 20], 'the hand-placed span')
})
check('switching the line on takes the span back', () => {
prun('select_span(10, 20)')
panel.win.id_time_travel.checked = true
prun('toggle_time_travel()')
eq(prun('span.a === span.b'), true, 'the line should hold a single version')
eq(prun('span.a'), prun('travelling_vi'), 'and it should be the one it crosses')
panel.win.id_time_travel.checked = false
prun('update_time_travel()')
})
check('switching the line off lets go of the span it held', () => {
panel.win.id_time_travel.checked = true
prun('travelling_vi = null; update_time_travel()')
ok(prun('span') !== null, 'the line should have placed a span')
panel.win.id_time_travel.checked = false
prun('toggle_time_travel()')
eq(prun('span'), null, 'the span outlived the line')
})
check('a span placed by hand outlives the line being redrawn', () => {
prun('select_span(10, 20)')
prun('update_time_travel()')
eq(prun('[span.a, span.b]'), [10, 20], 'the hand-placed span')