-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpanel.js
More file actions
1300 lines (1176 loc) · 56.1 KB
/
Copy pathpanel.js
File metadata and controls
1300 lines (1176 loc) · 56.1 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
// Error handling
window.onerror = function (message, source, lineno, colno, error) {
const errorContainer = document.getElementById('error-container');
const errorMessageElement = document.getElementById('error-message');
errorMessageElement.textContent = error.stack;
errorContainer.style.display = 'block';
};
let versions = []
// The panel keeps its own copy of the document. History arrives as dt bytes
// -- a few hundred kilobytes for a document whose expanded patches would be
// megabytes -- and every question about it is then answered locally, with no
// messaging between the panel and the page.
let dt_doc = null
let dt_ready = null
function ensure_dt() {
if (!dt_ready) dt_ready = fetch('dt_bg.wasm')
.then(r => r.arrayBuffer())
.then(buf => { initSync({ module: buf }) })
return dt_ready
}
function reset_dt_doc() {
if (dt_doc) try { dt_doc.free() } catch (e) {}
dt_doc = null
}
let raw_messages = []
let headers = {}
let get_failed = ''
let last_version = ''
let last_parents = ''
let backgroundConnection = null
window.onload = function () {
connect()
};
window.onresize = () => update()
function connect() {
backgroundConnection = chrome.runtime.connect({ name: "braid-devtools-panel" })
backgroundConnection.onMessage.addListener(add_message)
// Opening the panel says what it would ask for, without asking for it.
// Connecting a page that never advertised Braid costs it a second GET,
// which can rotate a csrf token or spend a single-use url, so the page
// sniffs for Braid and only an explicit ask overrules that.
let asked_for_it = false
// Everything the page needs to ask for what the panel is showing.
function settings(cmd) {
return { cmd, asked_for: asked_for_it, content_type: content_type_select.value, merge_type: merge_type_select.value, subscribe: subscribe_request.checked, encoding_dt: encoding_request.checked, ...(version_request.value ? { version: version_request.value } : {}), ...(parents_request.value ? { parents: parents_request.value } : {}), edit_source: edit_source.checked }
}
// Said on every connect, not only on every change. The background holds a
// copy to hand each page as it loads, but it is an event page and forgets
// whenever it sleeps -- and the reconnect that follows is what brings the
// settings back. Until this, getting them back meant toggling a control
// off and on again.
backgroundConnection?.postMessage({ ...settings('init'), tab_id: chrome.devtools.inspectedWindow.tabId })
function rerequest() {
asked_for_it = true
backgroundConnection?.postMessage(settings("rerequest"));
last_version = version_request.value
last_parents = parents_request.value
get_failed = ''
update()
update_show_resubmit()
}
resubmit_button.onclick = rerequest
content_type_select.onchange = rerequest
merge_type_select.onchange = () => { update_encoding_enabled(); rerequest() }
encoding_request.onchange = rerequest
update_encoding_enabled()
backgroundConnection.onDisconnect.addListener(() => {
// Let go of the dead port. Every send here is written `?.postMessage`,
// which asks whether there is a port at all -- posting to one that has
// disconnected throws, and the background is an event page that
// disconnects whenever it dozes off.
backgroundConnection = null
setTimeout(connect, 500)
});
// Whatever the old port failed to deliver never arrived, so say the
// selection over rather than leaving the page showing something else.
last_diff = null
show_span_diff()
id_raw_messages.onchange = () => { update_history_controls(); update() }
id_time_travel.onchange = toggle_time_travel
id_show_deletions.onchange = () => show_span_diff()
update_history_controls()
subscribe_request.onchange = () => {
if (subscribe_request.checked) {
version_request.value = ''
parents_request.value = ''
}
rerequest()
}
version_request.oninput = update_show_resubmit
parents_request.oninput = update_show_resubmit
update_show_resubmit()
function update_show_resubmit() {
if (version_request.value || parents_request.value) {
subscribe_request.checked = false
subscribe_request.disabled = true
} else {
subscribe_request.disabled = false
}
resubmit_button.style.display = (last_version != version_request.value || last_parents != parents_request.value) ? 'block' : 'none'
}
edit_source.oninput = () => {
// Showing the source swaps the view in place rather than reconnecting,
// so it keeps its own cmd -- but it carries the settings like the rest,
// so the background has them for the next page either way.
if (edit_source.checked) {
asked_for_it = true
backgroundConnection?.postMessage(settings("edit_source"))
} else rerequest()
}
}
function add_message(message) {
// Handle message from content script here
// console.log("Received message in devtools:", message);
if (message.action == 'init') {
// Only a new sync throws the old history away. The page also says all
// this when a panel asks it to, which every reconnect does, and that
// is the same history described again rather than a new one -- taking
// it for a page load rebuilt the view and flashed the page every time
// the port came back.
if (message.fresh) {
// Keeping the old document would merge two unrelated histories
// into one graph, and leave the incoming one nothing to report.
reset_dt_doc()
// The span named versions of the history being replaced. Saying it
// came from the line leaves the time-travel box alone: that is a
// setting rather than a selection, and takes hold on its own.
if (span) select_span(null, null, true)
travelling_vi = null
}
versions = message.versions
raw_messages = message.raw_messages
if (message.headers) headers = message.headers
get_failed = message.get_failed
update()
} else if (message.action == 'new_version') {
if (message.remove_count) versions.splice(versions.length - message.remove_count, message.remove_count)
if (message.remove_version) {
for (let i = versions.length - 1; i >= 0; i--) {
if (versions[i].version.length === message.remove_version.length && versions[i].version.every((v, i) => v === message.remove_version[i])) {
versions.splice(i, 1)
break
}
}
}
if (message.version) versions.push(message.version)
// A history dump arrives as one message holding many versions, rather
// than a message each, so the view is built once instead of per row
if (message.batch) for (let v of message.batch) versions.push(v)
if (message.override_versions) versions = message.override_versions
// Only rebuild the view that shows versions. The raw view catches
// up when its checkbox toggles, which calls update() itself
if (!id_raw_messages.checked) update()
} else if (message.action == 'dt_history') {
// A chunk of history in raw dt bytes. Merging it here and expanding it
// here costs one message, instead of one per version it contains.
ensure_dt().then(() => {
if (!dt_doc) dt_doc = new Doc('panel')
let bytes = Uint8Array.from(atob(message.bytes), c => c.charCodeAt(0))
let before = dt_doc.getRemoteVersion().map(x => x.join('-')).sort()
dt_doc.mergeBytes(bytes)
for (let u of dt_doc.getUpdates(before.length ? before : null))
versions.push({ method: "GET", version: u.version,
parents: u.parents, patches: u.patches })
if (!id_raw_messages.checked) update()
}).catch(e => console.error('dt_history failed:', e))
} else if (message.action == 'new_headers') {
headers = message.headers
update()
} else if (message.action == 'braid_in' || message.action == 'braid_out') {
raw_messages.push(message.data)
if (id_raw_messages.checked) update()
} else if (message.action == 'get_failed') {
get_failed = message.get_failed
update()
}
}
let update_requested = false
function update() {
if (!update_requested) {
update_requested = true
requestAnimationFrame(() => {
update_requested = false
raw_update()
})
}
}
function raw_update() {
let was_scrolled_to_bottom = isScrolledToBottom(id_messages)
for (let [k, v] of Object.entries({
'subscribe': 'subscribe_response',
'encoding': 'encoding_response',
'version': 'version_response',
'parents': 'parents_response',
'merge-type': 'merge_type_response',
})) {
// Version ids are quoted on the wire; display them bare
window[v].textContent = (headers[k] ?? '').replace(/"/g, '')
}
var full_content_type = headers['repr-type'] ?? headers['content-type'] ?? ''
// application/http-history frames the subscription; it is not the repr
if (full_content_type.startsWith('application/http-history')) full_content_type = ''
window.content_type_response.textContent = full_content_type.split(';')[0].trim()
window.content_type_response.title = full_content_type
window.subscribe_response.textContent = '' + (headers.subscribe != null)
update_encoding_enabled()
window.error_d_label.style.display = get_failed ? 'inline' : 'none'
window.error_d.textContent = get_failed
// A version and parents follow you to the next url, because resources
// that move in step name their versions alike and stepping through them
// together is the point. A resource that has never heard of the version
// says so, and the ask goes red and stays put, rather than being cleared
// out from under you or quietly dropped.
var refused = headers[':status'] >= 400
for (let box of [version_request, parents_request]) {
box.style.color = refused && box.value ? '#c00' : ''
box.title = refused && box.value
? `this resource answered ${headers[':status']}` : ''
}
edit_source_d.style.display = (headers['repr-type'] ?? headers['content-type'])?.startsWith('text/html') ? 'flex' : 'none'
if (!id_raw_messages.checked && versions?.length) {
layout_history()
render_history_window()
} else if (id_raw_messages.checked && raw_messages?.length) {
// Whatever was there is replaced, so the geometry describing it goes
layout = null
id_messages.innerHTML = ''
id_messages.style.display = 'block'
let d = document.createElement('pre')
d.textContent = raw_messages.join('')
//d.style.background = `rgb(41,42,45)`
d.style.borderRadius = '3px'
d.style.margin = '3px'
d.style.padding = '3px'
d.style.textWrap = 'wrap'
id_messages.append(d)
} else {
layout = null
id_messages.innerHTML = ''
let d = document.createElement('div')
d.textContent = 'nothing to show'
d.style.cssText = `margin:10px`
id_messages.append(d)
}
if (was_scrolled_to_bottom) {
id_messages.scrollTop = id_messages.scrollHeight
if (layout) render_history_window()
}
if (!layout) update_time_travel()
}
// dt binary encoding only applies to the dt merge-type, whether chosen
// in the menu or served as the page's default
function update_encoding_enabled() {
encoding_request.disabled = !(merge_type_select.value === 'dt' ||
headers['merge-type'] === 'dt')
}
function isScrolledToBottom(element) {
// An unscrollable view counts as at-the-top, not at-the-bottom
return element.scrollHeight > element.clientHeight
// Fractional scroll positions (from display scaling) never compare
// exactly equal, so allow a couple pixels of slop
&& element.scrollHeight - element.scrollTop - element.clientHeight < 3;
}
// The history view can run to tens of thousands of versions, which is far more
// than a browser will lay out at any comfortable speed. So the geometry of the
// whole history is worked out in plain arrays, and only the rows that fall
// inside the scroll viewport are ever put into the DOM.
//
// Rows are not all the same height, because a patch's content wraps over as
// many lines as it needs. Nothing is measured off the page to find out how
// many: the content column is monospace and breaks at exactly the column
// edge, so the line count follows from the string and the column width. Row
// tops are then a running total, and the rows crossing the viewport are found
// by binary search.
// Leading within a row, at about 1.4x the monospace size the browser picks.
// Lines of one patch should read as one block.
const LINE_H = 18
// The gutter between rows. Separation between versions comes from this rather
// than from stretching the leading, so a multi-line patch stays a paragraph.
const ROW_PAD = 10
const HEADER_H = 34
// The proportional face the version identifiers are drawn in
const LABEL_FONT = 'font-family:Arial,sans-serif;font-size:medium;'
const LANE_W = 64
// Room either side of the version DAG. The DAG column doubles as the region a
// span of time is dragged out of, so it gets a little space to grab hold of.
const LANE_PAD = 10
const DAG_W = LANE_PAD + LANE_W + LANE_PAD
const DOT_R = 6
// Rows kept rendered past each edge of the viewport, so that a small scroll
// reveals rows that are already there.
const OVERSCAN_PX = 250
// One string for the monospace cells, shared by the measuring and the drawing
const MONO = 'font-family:monospace'
// How far an inverse-video label's background reaches past its own text. Both
// the label and the column around it give this back as negative margin, so
// nothing on the row moves to make room for it.
const BADGE_PAD_X = 5, BADGE_PAD_Y = 3
// Every span of time selected, as pairs of indices into layout.vs, inclusive
// and in either order until normalized. A click or a drag selects one; holding
// the platform's multi-select key starts another alongside the ones already
// there, and the page then shows what each of them changed, one after another.
let spans = []
// The span a drag is working on, which is always the last of them
let span = null
// A drag in progress: which end of the span is following the mouse
let drag = null
// The version the time-travel line is crossing, when the line is on. The span
// follows it, so this only records what the line last landed on.
let travelling_vi = null
// What the last layout pass worked out. Everything the renderer needs to draw
// any row, without consulting the DOM or the version list again.
let layout = null
function esc(s) {
return ('' + s).replace(/[&<>"]/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"' })[c])
}
// The width a string takes in a given style. Used a handful of times per
// layout, on the longest string in each column, to fix the column widths.
// Widths have to be fixed: a table that sizes its columns to their contents
// would need every row in the DOM, which is the thing we are avoiding.
function measure_text(text, style) {
let d = document.createElement('div')
d.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;' + style
d.textContent = text
document.body.append(d)
let w = d.offsetWidth
d.remove()
return w
}
function longest(strings) {
let best = ''
for (let s of strings) if (s && s.length > best.length) best = s
return best
}
// A pass over the history builds the geometry of every row. That pass is
// linear, and on a large document it is long enough to be felt, so it is not
// redone when all that has happened is that versions were appended: the state
// it works from lives in the layout object, and a later pass picks it up where
// the previous one stopped. Anything else -- a new sync, a resize, a version
// too wide for the columns it was laid out against -- starts over.
function new_layout() {
return {
src: versions, n_consumed: 0,
vs: [], seen: Object.create(null), leaves: new Set(),
rows: [], row_tops: [HEADER_H], row_of: [], circles: [], edges: [],
version_xs: {}, version_ys: {}, v_to_multiv: {}, actor_to_seqs: {},
actor_to_color: {}, actor_color_angles: [], last_actor_angle: 0,
last_x: 0.5, last_v: '',
cols: null, char_w: 0, per_line: 1, widest: { version: '', unit: '', range: '' },
// What the imaginary tip added, so it can be taken off again
merge: null,
}
}
function layout_history() {
let L = layout
// Appending to the same array is the case worth continuing from. A new
// array means a new sync, and nothing carries over.
if (!(L && L.src === versions && versions.length >= L.n_consumed)) L = null
if (L) {
remove_final_merge(L)
// A version wider than the columns it would be laid out against
// shifts every row that came before it, so that pass is abandoned.
if (!extend_layout(L)) L = null
}
if (!L) {
L = new_layout()
measure_columns(L)
extend_layout(L)
}
add_final_merge(L)
L.height = L.row_tops[L.rows.length]
layout = L
}
// Column widths are fixed. A table that sized its columns to their contents
// would need every row in the DOM, which is the thing being avoided here.
function measure_columns(L) {
let label_style = LABEL_FONT
L.widest = {
version: longest(versions.map(v => '' + v.version || 'root')),
unit: longest(versions.flatMap(v => v.patches.map(p => p.unit))) || 'text',
range: longest(versions.flatMap(v => v.patches.map(p => range_text(p)))) || '000:000',
}
L.cols = {
version: measure_text(L.widest.version, label_style) + 10,
unit: measure_text(L.widest.unit, MONO) + 18,
range: measure_text(L.widest.range, MONO) + 18,
}
// The column has to fit the longest identifier in the document, but the
// band should hug what is typically on screen, so that one unusually long
// peer name does not stretch it out across empty space. Sample identifiers
// across the history, measure what they actually render as, and take a
// high percentile of that. Ranking by string length would not do: seq
// numbers gain digits as a document grows, so most identifiers end up at
// the longest length and the percentile lands on the maximum anyway.
let step = Math.max(1, Math.floor(versions.length / 100))
let widths = []
for (let i = 0; i < versions.length; i += step)
widths.push(measure_text('' + versions[i].version || 'root', LABEL_FONT))
widths.sort((a, b) => a - b)
L.band_w = DAG_W + Math.min(L.cols.version,
(widths[Math.floor(widths.length * 0.9)] || 0) + 8)
// How many characters fit across the content column, and so how many
// lines a given string of content will take.
L.char_w = measure_text('0'.repeat(100), MONO) / 100
let content_w = Math.max(60, (id_messages.clientWidth || 800)
- LANE_W - L.cols.version - L.cols.unit - L.cols.range - 14 - 24)
L.per_line = Math.max(1, Math.floor(content_w / L.char_w))
}
function range_text(p) {
return p.unit == 'text' ? p.range.slice(1, -1) : p.range
}
// Whether a version still fits the columns. Only a string longer than the
// longest one seen so far can fail, so measuring is rare.
function fits_columns(L, v) {
let check = (col, str, style, slack) => {
if (!str || str.length <= L.widest[col].length) return true
if (measure_text(str, style) + slack > L.cols[col]) return false
L.widest[col] = str
return true
}
if (!check('version', '' + v.version || 'root',
'font-family:Arial,sans-serif;font-size:medium;', 10)) return false
for (let p of v.patches) {
if (!check('unit', p.unit, MONO, 18)) return false
if (!check('range', range_text(p), MONO, 18)) return false
}
return true
}
function line_count(L, content) {
if (!content) return 1
let n = 0
for (let line of content.split('\n'))
n += Math.max(1, Math.ceil(line.length / L.per_line))
return n
}
// Parents name individual events, but a row can cover a run of them, so a
// named parent has to be resolved to the row that actually contains it.
function get_real_event(L, e) {
try {
let [actor, seq] = decode_version(e)
let seqs = L.actor_to_seqs[actor]
if (!seqs?.length) return
let lo = 0, hi = seqs.length
while (lo < hi) {
let mid = (lo + hi) >> 1
if (seqs[mid] < seq) lo = mid + 1
else hi = mid
}
if (lo < seqs.length) return actor + '-' + seqs[lo]
} catch (e) {}
}
function get_real_parents(L, parents) {
if (!parents?.length) return { '': true }
let real_parents = {}
for (let p of parents) {
let real_p = get_real_event(L, p)
if (!real_p) continue
let unchanged = real_p === p
real_p = L.v_to_multiv[real_p]
if (!real_p) continue
real_parents[real_p] = unchanged
}
return real_parents
}
function extend_layout(L) {
for (let i = L.n_consumed; i < versions.length; i++) {
let v = versions[i]
let v_string = '' + v.version
// The same version can arrive more than once; show it once.
if (L.seen[v_string]) continue
if (!fits_columns(L, v)) return false
L.seen[v_string] = true
L.leaves.add(v_string)
if (v.parents) {
for (let p of v.parents) L.leaves.delete(p)
L.leaves.delete('' + v.parents)
}
place(L, v, v_string)
}
L.n_consumed = versions.length
return true
}
// Give a version its rows, its column in the lanes, and the edges up to its
// parents.
function place(L, v, v_string) {
let i = L.vs.length
L.vs.push(v)
let actor = v_string.split('-')[0]
if (!L.actor_to_color[actor]) {
let angle = get_new_angle(L.actor_color_angles, L.last_actor_angle)
L.actor_color_angles.push(angle)
L.last_actor_angle = angle
L.actor_to_color[actor] = angle_to_color(angle)
}
let color = L.actor_to_color[actor]
// A version takes one row per patch, and at least one row even when it has
// no patches at all. row_tops[r] is the top of row r, and one past the end
// is the bottom of the last row.
L.row_of[i] = L.rows.length
let ps = v.patches
let add_row = (pi, lines) => {
L.rows.push({ vi: i, pi })
L.row_tops.push(L.row_tops[L.rows.length - 1] + LINE_H * lines + ROW_PAD)
}
if (!ps.length) add_row(0, 1)
else for (let k = 0; k < ps.length; k++) add_row(k, line_count(L, ps[k].content))
// A version whose only parent is the version just above it stays in the
// same column; anything else steps sideways by an amount derived from its
// own name, so a branch keeps its column for as long as it runs.
let real_parents = get_real_parents(L, v.parents)
let rpa = Object.keys(real_parents)
let x
if (rpa.length === 1 && rpa[0] === L.last_v) {
x = L.last_x
} else {
x = L.last_x + 0.25 + fastHashToUnit(v_string) * 0.5
if (x > 1) x -= 1
}
L.last_v = v_string
L.version_xs[v_string] = L.last_x = x
let y = L.row_tops[L.row_of[i]] + ROW_PAD / 2 + (LINE_H - 2 * DOT_R) / 2
L.version_ys[v_string] = y
L.circles.push({ x, y, color })
if (i) for (let [pv, unchanged] of Object.entries(real_parents)) {
let py = L.version_ys[pv]
if (py == null) continue
L.edges.push({
x, px: L.version_xs[pv], color, dashed: !unchanged,
top: py + DOT_R, h: Math.max(1, y - py),
})
}
if (v.version !== 'final merge')
for (let e of v.version) {
L.v_to_multiv[e] = v_string
try {
let [a, seq] = decode_version(e)
if (!L.actor_to_seqs[a]) L.actor_to_seqs[a] = []
sorted_insert(L.actor_to_seqs[a], seq)
} catch (err) {}
}
}
// A history with more than one leaf has no single tip to draw the lanes into,
// so it gets an imaginary one that merges them. It depends on the whole leaf
// set, so each pass takes off the one the pass before it added.
function add_final_merge(L) {
if (L.leaves.size <= 1) return
L.merge = { vs: L.vs.length, rows: L.rows.length, edges: L.edges.length,
last_x: L.last_x, last_v: L.last_v }
place(L, { version: 'final merge', parents: [...L.leaves], patches: [] }, 'final merge')
}
function remove_final_merge(L) {
let m = L.merge
if (!m) return
L.vs.length = L.row_of.length = L.circles.length = m.vs
L.rows.length = m.rows
L.row_tops.length = m.rows + 1
L.edges.length = m.edges
L.last_x = m.last_x
L.last_v = m.last_v
delete L.version_xs['final merge']
delete L.version_ys['final merge']
L.merge = null
}
// Ctrl adds to a selection everywhere except the mac, where ctrl-click is a
// synthetic right-click and opens the context menu, so there it has to be cmd.
const MAC = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent)
const adding_to_selection = e => MAC ? e.metaKey : e.ctrlKey
// Dragging out a span of time in the gutter. A fresh drag on empty gutter
// starts a new span; grabbing an edge moves that edge; grabbing the body
// slides the whole span while keeping its length.
function install_gutter(body) {
let gutter = document.getElementById('history_gutter')
let autoscroll = null, autoscroll_timer = null
let y_of = (e) => e.clientY - body.getBoundingClientRect().top
gutter.onmousedown = (e) => {
if (!layout) return
e.preventDefault()
let vi = version_at(y_of(e))
let handle = e.target.dataset?.grip
// Which span was pressed on, by the grip if one was hit and by the
// version under the mouse otherwise, so the gaps between rows count too
let pressed = handle ? +e.target.dataset.span
: spans.findIndex(s => vi >= Math.min(s.a, s.b) && vi <= Math.max(s.a, s.b))
// The modifier both adds and takes away, and where it is pressed says
// which. On a span already selected it takes away: moving from here
// carves a stretch out of everything it crosses, and letting go
// without having moved takes the whole span it landed on.
if (adding_to_selection(e) && pressed >= 0) {
drag = { mode: 'subtract', cursor: 'crosshair', from: vi, y: e.clientY,
pressed, moved: false, before: spans.slice() }
} else if (adding_to_selection(e)) {
// Anywhere else it starts another alongside the ones already
// there, which can then be dragged out like any other
add_span(vi, vi)
drag = { mode: 'edge', cursor: 'ns-resize', anchor: vi, y: e.clientY }
} else {
// Whichever span was grabbed becomes the one the drag works on,
// the last of them, so the others sit still while it moves.
if (handle && pressed >= 0 && pressed < spans.length)
spans.push(...spans.splice(pressed, 1)), span = spans[spans.length - 1]
if (handle === 'top') drag = { mode: 'edge', cursor: 'ns-resize',
anchor: Math.max(span.a, span.b), y: e.clientY }
else if (handle === 'bottom') drag = { mode: 'edge', cursor: 'ns-resize',
anchor: Math.min(span.a, span.b), y: e.clientY }
else if (handle === 'body') drag = { mode: 'move', cursor: 'grabbing', from: vi,
y: e.clientY, y0: y_of(e), a: span.a, b: span.b }
else {
// Drawing a new span is dragging its far edge outwards
drag = { mode: 'edge', cursor: 'ns-resize', anchor: vi, y: e.clientY }
select_span(vi, vi)
}
}
document.body.style.cursor = drag.cursor
autoscroll_timer = setInterval(autoscroll, 16)
// The grips carry their own cursors, which outrank anything set on an
// ancestor, so pressing the button has to draw again for the hand to
// close. Waiting for the first movement would leave it open on a press
// that never turns into a drag.
render_history_window()
}
// Carving is worked out from the spans as they stood when the press began,
// so dragging back over what was just taken puts it back.
let carve_to = (vi) => {
drag.moved = true
spans = subtract_range(drag.before,
Math.min(drag.from, vi), Math.max(drag.from, vi))
commit_selection()
}
document.addEventListener('mousemove', (e) => {
if (!drag || !layout) return
drag.y = e.clientY
let vi = version_at(y_of(e))
if (drag.mode === 'subtract') carve_to(vi)
else if (drag.mode === 'edge') drag_span(drag.anchor, vi)
else {
// Slide both ends by the same amount, stopping at the ends of
// history rather than letting the span shorten against them
let lo = Math.min(drag.a, drag.b), hi = Math.max(drag.a, drag.b)
let shift = Math.max(-lo, Math.min(vi - drag.from, layout.vs.length - 1 - hi))
drag_span(lo + shift, hi + shift)
}
})
document.addEventListener('mouseup', () => {
if (!drag) return
let was = drag
drag = null
document.body.style.cursor = ''
clearInterval(autoscroll_timer)
// A press with the modifier that never went anywhere is a click, and
// takes the whole span it landed on. Nothing was carved, so the index
// it was pressed on still names the same span.
if (was.mode === 'subtract') {
if (!was.moved && was.pressed >= 0 && was.pressed < spans.length)
spans.splice(was.pressed, 1)
return commit_selection()
}
// Spans dragged into one another have been drawn as one band all
// along; now they become one. The page is told again either way, since
// what it was told last was worked out from the merged spans and has
// not changed.
bloop_spans()
// The gutter and its grips take their cursors from whether a drag is
// running, and that is decided at render time, so ending one has to
// draw again or the cursor of the finished drag stays on screen.
render_history_window()
})
// Dragging above or below the view scrolls it, so a span can reach further
// than one screenful. The speed grows with how far past the edge the mouse
// has gone, the way selecting text does.
autoscroll = () => {
if (!drag || !layout) return
let r = id_messages.getBoundingClientRect()
let over = drag.y < r.top ? drag.y - r.top
: drag.y > r.bottom ? drag.y - r.bottom : 0
if (!over) return
id_messages.scrollTop += Math.sign(over) * Math.min(40, 4 + Math.abs(over) / 4)
let vi = version_at(drag.y - body.getBoundingClientRect().top)
if (drag.mode === 'subtract') carve_to(vi)
else if (drag.mode === 'edge') drag_span(drag.anchor, vi)
else render_history_window()
}
}
// The span, normalized, or null. Selecting is separated from acting on the
// selection so that dragging can update the highlight on every mouse move
// without asking the page to redraw a diff each time.
// `from_line` marks a span the scroll line placed. Anything else is the user
// placing one by hand, which takes the line's job away from it.
function commit_selection(from_line) {
span = spans.length ? spans[spans.length - 1] : null
if (!from_line && id_time_travel.checked) {
id_time_travel.checked = false
travelling_vi = null
}
show_span_diff()
render_history_window()
}
// Spans that touch or overlap are one span. Two of them are drawn as one band
// anyway, and asking the page about both would have it say the same thing
// twice. Touching counts: [4,6] and [7,9] leave no version standing between
// them, so they cover the same stretch of history that [4,9] does.
function coalesce(spans) {
let out = []
for (let [lo, hi] of spans.map(s => [Math.min(s.a, s.b), Math.max(s.a, s.b)])
.sort((x, y) => x[0] - y[0])) {
let last = out[out.length - 1]
if (last && lo <= last.b + 1) last.b = Math.max(last.b, hi)
else out.push({ a: lo, b: hi })
}
return out
}
// Take a stretch of history out of everything selected. A span it lands in the
// middle of comes apart into the two ends that survive it, which is the only
// way to select a run of history with a hole in it.
function subtract_range(spans, lo, hi) {
let out = []
for (let s of spans) {
let a = Math.min(s.a, s.b), b = Math.max(s.a, s.b)
if (b < lo || a > hi) { out.push({ a, b }); continue }
if (a < lo) out.push({ a, b: lo - 1 })
if (b > hi) out.push({ a: hi + 1, b })
}
return out
}
// Run them together for good, once a drag has stopped moving them about. The
// one that was being held stays the one being held, inside whatever swallowed
// it, so a second drag carries on with the same span rather than another.
function bloop_spans() {
let merged = coalesce(spans)
if (merged.length === spans.length) return false
let held = span && Math.min(span.a, span.b)
spans = merged
let i = spans.findIndex(s => held != null && held >= s.a && held <= s.b)
if (i >= 0) spans.push(...spans.splice(i, 1))
span = spans[spans.length - 1] ?? null
return true
}
// Everything selected, replaced by this one span -- or by nothing at all
function select_span(a, b, from_line) {
spans = a == null ? [] : [{ a, b }]
commit_selection(from_line)
}
// Another span, kept alongside the ones already selected
function add_span(a, b) {
spans.push({ a, b })
commit_selection()
}
// Move the span a drag is working on, leaving the rest of them where they are
function drag_span(a, b) {
if (!spans.length) return select_span(a, b)
spans[spans.length - 1] = { a, b }
commit_selection()
}
// What the span changed: the text as it stood before its first version,
// marked up with everything its versions inserted and deleted. A span of one
// version therefore answers "what did this edit do?".
let last_diff = '', diff_queued = false
function show_span_diff() {
// Dropping the span is a one-off, and has to reach the page before the
// time-travel text that follows it, so it does not wait for a frame.
// Dragging is the opposite: it fires faster than the display refreshes,
// so those are coalesced.
if (!spans.length) return send_span_diff()
if (diff_queued) return
diff_queued = true
requestAnimationFrame(() => { diff_queued = false; send_span_diff() })
}
function send_span_diff() {
if (!spans.length) {
if (last_diff === '') return
last_diff = ''
return backgroundConnection?.postMessage({ cmd: 'show_diff', spans: [] })
}
// A frame passes between asking for this and working it out, and the
// layout can be thrown away in between -- a resize does it, so does a sync
// arriving with nothing in it. The spans then name rows that are not
// there. Nothing to say until it has been built again, and the page goes
// on showing what it already has.
if (!layout) return
let end = layout.vs.length - 1
// Read out in the order they sit in history, whatever order they were
// picked in, so the page walks them the same way the graph does. Run
// together first: spans that overlap would otherwise ask the page to step
// backwards between them, which is not a stretch of history at all.
let asked = coalesce(spans)
// A history that came back shorter leaves spans hanging off the end
.filter(s => s.a <= end)
.map(({ a: lo, b: hi }) => {
hi = Math.min(hi, end)
let before = layout.vs[lo].parents?.length ? layout.vs[lo].parents
: layout.vs[lo].version
// Nobody ever wrote the final merge, so a span reaching it ends at
// the leaves it draws together, which is where the document stands.
let after = layout.vs[hi].version === 'final merge' ? layout.vs[hi].parents
: layout.vs[hi].version
let digits = layout.vs[hi].patches?.[0]?.range?.match(/\d+/)
return { from_version: before, to_version: after,
at: digits ? 1 * digits[0] : null, key: lo + ':' + hi }
})
if (!asked.length) return
let key = asked.map(a => a.key).join(',') + ':' + id_show_deletions.checked
if (key === last_diff) return
last_diff = key
backgroundConnection?.postMessage({
cmd: "show_diff",
spans: asked.map(({ key, ...rest }) => rest),
colors: layout.actor_to_color,
show_deletions: id_show_deletions.checked,
})
}
function toggle_time_travel() {
// Forget where the line last was, so switching it on takes hold of the
// span again rather than deciding nothing has moved.
travelling_vi = null
// Switching the line off lets go of the span it was holding: that
// selection was the line's doing, and there is nothing left to keep it.
// Only this path clears it — a span placed by hand also leaves the box
// unchecked, and that one is the user's and stays.
if (!id_time_travel.checked) select_span(null)
update_time_travel()
}
// Raw messages replace the history view altogether, so there is nothing left
// to scroll through and nothing to have selected a span of. Any span that was
// showing goes with it, since it could no longer be seen or adjusted, and the
// controls that act on one say so by going grey.
function update_history_controls() {
let off = id_raw_messages.checked
if (off && span) select_span(null)
if (off && id_time_travel.checked) id_time_travel.checked = false
for (let [box, label] of [[id_time_travel, id_time_travel_label],
[id_show_deletions, id_show_deletions_label]]) {
box.disabled = off
label.style.opacity = off ? 0.4 : 1
}
}
// The dashed line sits across the middle of the view, and the span follows it:
// whichever version crosses the line is the one selected, so scrolling the
// history plays the document back one edit at a time. What you see of it is
// then the same thing a hand-placed span shows.
function update_time_travel() {
let line = document.getElementById('history_line')
if (!line) return
update_history_controls()
if (!id_time_travel.checked || id_time_travel.disabled || !layout) {
line.style.display = 'none'
travelling_vi = null
return
}
let mid = id_messages.scrollTop + id_messages.clientHeight / 2
line.style.display = 'block'
line.style.top = mid + 'px'
let vi = version_at(mid)
if (vi === travelling_vi) return
travelling_vi = vi
select_span(vi, vi, true)
}
function version_top(vi) { return layout.row_tops[layout.row_of[vi]] }
function version_bottom(vi) {
return layout.row_tops[vi + 1 < layout.vs.length
? layout.row_of[vi + 1] : layout.rows.length]
}
// The version covering a point on the page, clamped to the ends.
function version_at(y) {
let tops = layout.row_tops
let lo = 0, hi = layout.rows.length - 1
while (lo < hi) {
let mid = (lo + hi) >> 1
if (tops[mid + 1] <= y) lo = mid + 1
else hi = mid
}
return layout.rows[lo].vi
}
// The rows and lane segments that fall inside the viewport, and nothing else.
// Everything is written as one string of HTML per container: setting innerHTML
// once is far cheaper than appending a few hundred nodes one at a time.
function render_history_window() {
if (!layout) return
let { vs, rows, row_of, row_tops, circles, edges, cols, actor_to_color } = layout
let body = document.getElementById('history_body')
if (!body) {
id_messages.style.display = 'block'
id_messages.style.position = 'relative'
id_messages.innerHTML =
`<div id="history_body" style="position:relative">` +
`<div id="history_band" style="position:absolute;left:0;top:0;` +
`height:100%;pointer-events:none"></div>` +
`<div id="history_lanes" style="position:absolute;left:${LANE_PAD}px;top:0;` +
`width:${LANE_W}px;height:100%;pointer-events:none"></div>` +
`<div id="history_rows"></div>` +
`<div id="history_gutter" style="position:absolute;left:0;top:0;` +
`height:100%;cursor:ns-resize;z-index:1"></div>` +
`<div id="history_line" style="position:absolute;left:0;right:0;height:0;` +
`border-top:1px dashed #e08b00;display:none;pointer-events:none;z-index:2"></div>` +
`</div>`
body = document.getElementById('history_body')
// The rows themselves are ordinary selectable text, so that a range or
// a piece of content can be copied out. Clicking among them, without
// having selected any of that text, drops the span.
body.onclick = (e) => {
if (e.target.closest?.('#history_gutter')) return
if (window.getSelection?.().toString()) return
select_span(null, null)