-
Notifications
You must be signed in to change notification settings - Fork 1
/
graph.js
2245 lines (1643 loc) · 88.8 KB
/
graph.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
// ---------
// INIT
// ---------
// Constants and variables
// Note: colorImageNameDefinitions values are echoed to console, when generating colored images with script 'colorize.bash'
const colorImageNameDefinitions = [
'red',
'blue',
'orange',
'purple',
'salmon',
'orange4',
'tan',
'goldenrod1',
'olive',
'LawnGreen',
'PaleTurquoise1',
'DeepSkyBlue'
];
let STROKE = { color: '#888', width: 3}; // Line color
var MODE = 'git-log-graph'; // Default, is set by state.graph.swimlane;
const UNIQUE_EOL = 'X3.17X'; // Used as EOL in git log to split rows to make it improbable to mix up output with EOL
const unsetNodeImageFile = 'images/circle_grey.png';
var gui = require("nw.gui");
var os = require('os');
var fs = require('fs');
const simpleGit = opener.simpleGit;
var util = require('./util_module.js'); // Pragma-git common functions
const pathsep = require('path').sep; // Os-dependent path separator
var win
var sumFound;
var graphContent = ''; // This is where output is collected before putting it into graphContent element
var dateContent = ''; // This is where date output is collected for swim-lane version of Graph
var branchNames; // map branchname => index 0, 1, 2, ... calculated in drawGraph
var mapVisibleBranchToTopCommit; // map branchName to hash of newest commit
var mapTopCommitToBranchName; // reverse, map first commit on branch to branchName
var childMap ; // Store mapping from parent to child hashes
var nodeMap; // Map hash to commit (same object as in commitArray, but can be looked up)
var commitArray; // Array with same commits as in nodeMap
var columnOccupiedStateArray; // Array used to mark occupied columns, stores last known occupied row-number of branch segment
const BUFFERTCOLS = ' '; // Allows to look to the left of current character
const BUFFERTROW = ' ';
let NUMBER_OF_KNOWN_BRANCHES = 0; // This marks the last branch with known branchname in branchNames map
var lastSelectedBranchName = ''; // Used to set default when renaming commit's branch name
var infoNodes = []; // An array of nodes that have been redrawn with mouse-over svg node circle
const FIRSTPASSLENGTH = 70; // Number of git-log rows for first pass drawing
const INFINITY = 100000000; // Used in first pass of drawing when position of parent node is not known (because of truncated git-log)
// GUI constants
// Node image
const IMG_H = 12;
const IMG_W = 12;
// Grid dimensions
const COL_WIDTH = 20; // 20
const LEFT_OFFSET = 10;
const TOP_OFFSET = 0.5 * IMG_H;
var ROW_HEIGHT; // Read from CSS in drawGraph
const R = 15; // arc radius for branch and merge. Note : R <= COL_WIDTH & R <= ROW_HEIGHT
// Global for whole app
var state = global.state; // internal name of global.state
var localState = global.localState;
// Global in this window
let history = '';
var graphText; // Output from git log
var COMPRESS;
const DEBUG = state.graph.debug; // true = show debug info on commit messages
let firstRun = true;
var showLongHash = state.graph.showLongHash; // Default display format within graph window (popup)
//
// Functions
//
// Start
async function injectIntoJs(document){
win = gui.Window.get();
//
// Init
//
document.getElementById('showDate').checked = state.graph.showdate;
document.getElementById('showAll').checked = state.graph.showall;
document.getElementById('showHidden').checked = state.graph.showHiddenBranches;
document.getElementById('graph_mode_switch').checked = state.graph.swimlanes;
colorSwitchTexts(); // Set switch-text-colors (see graph.html)
// Create empty hiddenBranches list if undefined
if ( state.repos[state.repoNumber].hiddenBranches == undefined ){
state.repos[state.repoNumber].hiddenBranches = [];
}
if ( state.graph.swimlanes ){
MODE = 'swim-lanes';
}else{
MODE = 'git-log-graph';
}
// For systems that have multiple workspaces (virtual screens)
if ( win.canSetVisibleOnAllWorkspaces() ){
win.setVisibleOnAllWorkspaces( state.onAllWorkspaces );
}
let folder = state.repos[ state.repoNumber].localFolder;
//
// Read history
//
// History from Pragma-git (honoring settings)
// If --first-parent then off-branch commits will yield branch-number NaN, and be marked 'off-branch' by Pragma-git
// If not --first-parent, then all commits will be shown with commit number
history = await opener.gitHistory();
console.log(history);
// Commit log output format
const messageFormat = '--format=S=%s T=%aI D=%d H=%H P=%P B=%b N=%N' + UNIQUE_EOL; // %aI = author date, strict ISO 8601 format
//
// Set HTML
//
// Write header text
let repoName = opener.window.document.getElementById('top-titlebar-repo-text').innerText;
let branchName = opener.window.document.getElementById('top-titlebar-branch-text').innerText;
document.getElementById('repoName').innerText = repoName;
document.getElementById('branchName').innerText = branchName;
// Hide "Show hidden branches checkbox" visible only when hidden branches
if (( state.repos[state.repoNumber].hiddenBranches == undefined ) || ( state.repos[state.repoNumber].hiddenBranches.length == 0) ){
document.getElementById('hiddenBranchesDiv').style.contentVisibility = 'hidden' ;
}else{
document.getElementById('hiddenBranchesDiv').style.contentVisibility = 'visible' ;
}
//
// Create git-log commands
//
// Normal log command
let commands = [ 'log', '--date-order', '--oneline', '--pretty', messageFormat];
// Show all log command
if (state.graph.showall){
commands = [ 'log', '--branches', '--tags', '--date-order', '--oneline', '--pretty', messageFormat];
}
//
// Draw graph in HTML
//
try{
await simpleGit( folder).env('GIT_NOTES_REF', 'refs/notes/branchname').raw( commands, onLog);
function onLog(err, result ){graphText = result; console.log(result); };
}catch(err){
console.log(err);
}
// Draw full graph, and label current branch
let branchHistory = await readBranchHistory();
//
// Speed up by drawing
//
draw = SVG(); // Canvas -- global variable
let splitted; // Git-log row array
// Short part for pass 1, and all for pass 2
shortSplitted = graphText.split( UNIQUE_EOL + '\n').slice(0, FIRSTPASSLENGTH); // Lines first pass
allSplitted = graphText.split( UNIQUE_EOL + '\n');
if (firstRun){ // Speed up on when window is opened first time
if ( FIRSTPASSLENGTH > allSplitted.length ){
// Fewer lines than pass 1 => do everything in one pass
await drawGraph( document, allSplitted, branchHistory, history);
}else{
// first pass (top commits)
try{
await drawGraph( document, shortSplitted, branchHistory, history);
}catch(err){
}
// Wait for redraw (I have a feeling that it helps with lines being visible before circles)
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
await sleep(50);
// second pass (all)
await drawGraph( document, allSplitted, branchHistory, history); // Need to await so branchNames will be ready for drawBranchColorHeader
}
}else{
// If not second run -- draw everything in one pass (otherwise changing checkboxes and moves will make it jump)
await drawGraph( document, allSplitted, branchHistory, history);
}
// ColorHeader
document.getElementById('colorHeader').innerHTML = ''; // Clear 'colorHeader' html
drawBranchColorHeader( branchNames); // Append to 'colorHeader' html
// Populate branch-name edit menu
populateDropboxBranchSelection();
//Make MouseOver callbacks for node circles
makeMouseOverNodeCallbacks();
//
// Draw current and pinned commits
//
// Select current history commit in opened graph
try{
let divSelect = document.getElementById( localState.historyHash );
divSelect.classList.add('selected');
// Selected should not be graphed if
// - same commit is pinned
if (localState.pinnedCommit !== localState.historyHash ) {
localState.selectedDiv = divSelect;
}
}catch(err){
}
try{
opener.selectInGraph(localState.historyHash);
}catch(err){}
// Select pinned commit in opened graph
try{
let divPin = document.getElementById( localState.pinnedCommit );
divPin.firstElementChild.firstElementChild.src = PINNED_ENABLED_IMAGE; // Note -- defined in graph.html, dark/light mode image paths
divPin.classList.add('selected');
localState.pinnedDiv = divPin;
}catch(err){
}
// Finish
firstRun = false;
}
// Util
function stop(commit){ // Use for conditional-debug-stop in debugger
// Debug stop on commit selected in graph-window (use in conditional break-point in debugger)
//
// Create a conditional break point, and write condtion : stop(commit)
// (where variable commit is within scope)
return (opener.localState.historyHash == commit.hash)
}
async function readBranchHistory(){ // history of current branch (--first-parent)
let command = ['--first-parent'];
let history = '';
try{
await simpleGit(state.repos[state.repoNumber].localFolder).log( command, onHistory);
function onHistory(err, result){console.log(result); history = result.all; console.log(' ============ Found N = ' + history.length);}
}catch(err){
console.log(err);
}
return history;
}
function getColorFileName( name){
// Determine name of color class
let colorFileName = unsetNodeImageFile;
// Test, to show all colors on nodes without notes
//let colorName = colorImageNameDefinitions[ row % colorImageNameDefinitions.length ];
//colorFileName = `images/circle_colors/circle_${colorName}.png`;
if ( branchNames.has(name) ){
let colorNumber = branchNames.get(name) % colorImageNameDefinitions.length; // start again if too high number
let colorName = colorImageNameDefinitions[ colorNumber];
colorFileName = `images/circle_colors/circle_${colorName}.png`;
}
return colorFileName
}
function showBranch( branchName){ // True if branch should be shown (in contrast to hidden)
if (state.graph.showHiddenBranches ){
return true;
}else{
return !state.repos[state.repoNumber].hiddenBranches.includes(branchName );
}
}
// Callbacks
async function setPinned(hash, isPinned){ // Called from EventListener added in html
// This function updates main window
localState.pinnedCommit = hash;
localState.historyHash = hash;
localState.historyNumber = util.findObjectIndex(history,'hash', hash); // Will be NaN if off-branch
opener.drawPinImage(isPinned);
console.log(localState.pinnedDiv);
}
async function setHistoricalCommit(hash){ // Called prior to DOM update
// Get item number in history of current branch (or NaN if off-branch)
localState.historyNumber = util.findObjectIndex(history,'hash', hash);
// Set history in main window
localState.historyHash = hash;
localState.historyLength = history.length;
let commit = nodeMap.get(hash);
localState.historyString = opener.formatHistoryMessage( commit.date, commit.message, commit.messageBody)
// Off-branch is NaN, set to -1
if ( isNaN( localState.historyNumber ) ){
localState.historyNumber = -1;
}
await opener._setMode('HISTORY');
await opener._update();
}
function closeWindow(){
localState.graphWindow = false; // Show to main program that window is closed
// Store setting
state.graph.showdate = document.getElementById('showDate').checked;
state.graph.showall = document.getElementById('showAll').checked;
state.graph.swimlanes = document.getElementById('graph_mode_switch').checked; // True if swimlanes, false if compressed view
state.graph.showHiddenBranches = document.getElementById('showHidden').checked;
state.graph.showLongHash = showLongHash; // Value changed in popup window (but stored in variable instead, since popup may not be open)
opener.saveSettings();
// Remove from menu
opener.deleteWindowMenu('Graph');
win.close();
}
function toggleDate( show){
if (show){
document.getElementById('datesSwimLane').style.visibility = 'visible';
document.getElementById('datesSwimLane').style.width = 'fit-content';
}else{
document.getElementById('datesSwimLane').style.visibility = 'hidden';
document.getElementById('datesSwimLane').style.width = '0';
}
document.getElementById('graphContent').style.left = document.getElementById('mySvg').getBoundingClientRect()['x'] + document.getElementById('mySvg').getBoundingClientRect()['width'];
}
function updateImageUrl(image_id, new_image_url) {
var image = document.getElementById(image_id);
if (image)
image.src = new_image_url;
}
// Info popup functionality
function makeMouseOverNodeCallbacks(){ // Callbacks to show info on mouseover commit circles
// Add mouse events for each circle ( mouse out event is created when overlay image is done)
var arrElem = document.getElementsByTagName('image');
for (var i = 0; i < arrElem.length ; i++ ) {
arrElem[i].onmouseenter = mouseOverNodeCallback;
}
}
// State variables
var isMouseOverCommitCircle = false; // Used to stop infoBox from getting caught when leaving a commit circle before infoBox is drawn
var lockedNodeInfoWindow = false; // Used to keep node info window open until close-button pressed.
var currentImageNode = '';
var currentHash = '';
// callbacks
async function mouseOverNodeCallback(e) {
resetNodeSize(); // Clear previously resized nodes
// Set mouse position
isMouseOverCommitCircle = true;
// Lock window (stays open)
lockedNodeInfoWindow = true;
let hash = e.toElement.id.substring(4); // Because element id starts with "img_" followed by hash
await makePopupWindow(e, hash);
}
function mouseOverExistingNodeCallback(hash, isCallbackFromImg ){
console.log('mouseOverExistingNodeCallback');
let id = 'img_' + hash;
if ( (currentImageNode == id) && (isCallbackFromImg == true) ){
return
}
currentImageNode = id;
currentHash = hash;
let e = {};
e.toElement = {};
e.toElement.id = id;
e.target = {};
e.target.href = {};
e.target.href.baseVal = 'img_' + hash;
e.target.href.baseVal = document.getElementById(id).href.baseVal;
mouseOverNodeCallback(e);
}
function mouseLeavingNodeCallback(){
isMouseOverCommitCircle = false;
if (lockedNodeInfoWindow == true){
return
}
closeInfoBox();
return
};
// utility functions
async function makePopupWindow(e, hash){
let imageSrc = e.target.href.baseVal;
let commit = nodeMap.get(hash);
let maxColumn = commit.x;
// Get git author
let author = await gitCommitAuthor(hash);
console.log( 'commit : ' + commit.message );
// Parents
let parentHashes = commit.parents;
let ParentHeader = 'Parent';
if (parentHashes.length > 1)
ParentHeader = 'Parents';
// HTML
let html =``
// DEV : Displays where branch name info comes from (uncomment to use)
if (DEBUG) {
html = 'branch name : 1) from note = ' + commit.branchNameFromNote + ' 2) from decoration = ' + commit.branchNameFromDecoration + '<br>';
}
// Close button
html += `<img id="close-icon" style="width: 17px; float: right;"
onclick="lockedNodeInfoWindow = false; mouseLeavingNodeCallback();closeInfoBox()"
onmouseover="updateImageUrl('close-icon', 'images/button_close_hover.png');"
onmouseout= "updateImageUrl('close-icon', 'images/button_close_black.png');"
src="images/button_close_black.png">`
let branchName = commit.branchName;
let parenthesis = '';
if ( commit.hiddenBranchName ){
branchName = mapTopCommitToBranchName.get(commit.branchName); // Because branchName is the hash for hidden branches
parenthesis = ' (hidden)';
}
if ( commit.unknownBranchName ){
parenthesis = ' (' + commit.branchName.substring(0,6) + ')';
branchName = 'unknown '
}
// HTML Branch
html += `<h2>
<img class="node" src="${imageSrc}" style="display:inline; position : unset" >
<span> ${branchName} ${parenthesis} </span>
</h2>`
html += '<HR><BR>'
// HTML Commit
let mBody = '';
if (commit.messageBody.length > 0)
mBody += '<br> ' +
commit.messageBody.replaceAll('\n', '<br> ') +
'<br>';
html += ` <div>
<p>
<img class="node" src="${imageSrc}" style="display:inline; position : unset" >
<b><span style = "left: 30 px; position: relative"> ${commit.message}</span></b>
</p>
</div>
<BR><BR>`
// HTML Commit message body (if multiple lines in message)
html += `<span> ${mBody}</span><BR>`
html += `<div class="lightInfo" style="width: -webkit-fill-available;"> ${makeInnerHtmlFromHash(commit.hash)} </div><BR>`
html += `<div class="lightInfo" style="width: -webkit-fill-available;"> Author : <i> ${author} </i> </div><BR>
<div class="lightInfo" style="width: -webkit-fill-available;"> Time : <i> ${commit.date.substr(11,8)} ( ${commit.date.substr(0,10)} )</i> <BR><BR>
</div><BR><BR>`;
html += '<BR><HR><BR>'
// Change commit node size
sizeNodes( hash, IMG_H + 6);
infoNodes.push(hash); // Remember hash of resized node
// HTML Parents
html += `<B> ${ParentHeader}: </B> <BR><BR>`
for (let i = 0; i < parentHashes.length; i++){
// First commit has no parent hashes
if (parentHashes[i] == "")
continue
let id = "img_" + parentHashes[i];
let imageSrc = document.getElementById(id).href.baseVal;
html += `
<p>
<img class="node" src="${imageSrc}" style="display:inline; position : unset" >
<b> <span style = "left: 30 px; position: relative"> ${nodeMap.get( parentHashes[i] ).message} </span></b>
</p>`
// Change parent node size
sizeNodes( parentHashes[i], IMG_H + 6);
infoNodes.push(parentHashes[i]); // Remember hash of resized node
// Column
let commit = nodeMap.get(parentHashes[i]);
if ( commit.x > maxColumn)
maxColumn = commit.x;
}
// HTML Parent Hashes
for (let i = 0; i < parentHashes.length; i++){
html +='<BR><div class="lightInfo">';
html += makeInnerHtmlFromHash( parentHashes[i]);
html +='</div>';
}
html +='</div><BR><BR>';
// Selector short / long hash
let checked = '';
if (showLongHash){
checked = 'checked';
}
html += ` <span class="normal-text" style="display: inline;position: absolute; font-size: 11px; right: 20px; bottom: 10px;">
<span id="shortHash" style="color: var(--text)">short hash</span>
<label class="switch">
<input id="hash_length_switch" type="checkbox" class="slider round" onclick="updateInfoWindow();" ${checked}>
<span class="slider round"></span>
</label>
<span id="longHash" style="color: var(--dim-text)">long hash</span>
</span>`
// Display HTML
document.getElementById('displayedMouseOver').innerHTML = html;
document.getElementById('displayedMouseOver').style.visibility = 'visible';
// Set x to the right of lane
x = maxColumn;
let X0 = LEFT_OFFSET + (x + 1) * COL_WIDTH;
document.getElementById('displayedMouseOver').style.left = e.clientX + X0 + 20;
// Set y so that info box always on screen
let top = e.clientY - 15 - document.getElementById('displayedMouseOver').getBoundingClientRect().height;
if (top < 0)
top = e.clientY - 15;
document.getElementById('displayedMouseOver').style.top = top;
console.log( 'maxColumn : ' + maxColumn);
colorSwitchTexts()
};
function makeInnerHtmlFromHash( hash){ // Splits hash in two parts
const hashLength = 6;
let html = '';
let startHash = hash.substring(0,hashLength);
if (showLongHash){
// Make long
html += '<span>' + hash + '</span>';
}else{
html += '<span>' + startHash+ '</span>';
}
return html
}
function updateInfoWindow(){
// Called when pressing shift in graph.html
try{
showLongHash = document.getElementById('hash_length_switch').checked;
mouseOverExistingNodeCallback(currentHash, false) // false = means that it is not a callback from GUI
}catch(err){
}
}
function sizeNodes( hash, size){ // Make large node overlay image
let node = draw.node.getElementById( 'img_' + hash);
let commit = nodeMap.get(hash);
let X0 = commit.x * COL_WIDTH + 0.5;
let Y0 = commit.y * ROW_HEIGHT - 3;
// Position node ontop, in mySvg-space (which is zoomed due to zoom-box -- so that zoom follows automatically)
img = document.createElement('img');
img.style.left = X0;
img.style.top = Y0;
img.style.width = size;
img.style.height = size;
img.setAttribute('pointer-events', 'none')
img.setAttribute('z-index', 5000)
img.style.position='absolute';
img.src = node.href.baseVal;
img.setAttribute('onmouseleave', 'mouseLeavingNodeCallback()');
img.id='selectedImage_' + hash;
img.setAttribute('onmouseenter', 'console.log("ENTER");mouseOverExistingNodeCallback( "' + hash + '", true )' );
document.getElementById('mySvg').appendChild(img);
}
function resetNodeSize(){ // Reset node overlay image
// Reset node sizes
for (let i = 0; i < infoNodes.length; i++){
let hash = infoNodes[i];
let id='selectedImage_' + hash;
document.getElementById(id).remove();
}
infoNodes = [];
return
}
function closeInfoBox(){ // Info box closing
document.getElementById('displayedMouseOver').style.visibility = 'collapse';
resetNodeSize();
}
// Git
async function gitCommitAuthor(hash){
let folder = state.repos[ state.repoNumber].localFolder;
let text = '';
try{
let commands = [ 'show', '-s', '--format=%aN (%aE)', hash]; // Author
await simpleGit( folder).raw( commands, onGitCommitAuthor);
function onGitCommitAuthor(err, result ){
text = result;
// Remove parenthesis if email is empty
if (text.includes('()') ){
text = text.substring(0, text.length-3);
}
};
}catch(err){
console.log(err);
}
return text;
}
// Graphics
async function drawGraph( document, splitted, branchHistory, history){
// document : HTML document
// splitted : output from raw git log graph, as array (one row per array item)
// branchHistory : output from git log with --oneParent (used to find which commits are in current branch)
// history : the history after search, used to set different color for commits found/not found in Search
//
// SETUP
//
// Get ROW_HEIGHT from graph.html css
r = document.querySelector(':root');
ROW_HEIGHT = getComputedStyle(r).getPropertyValue('--textRowHeight');
// Initiate variables
var NUMBER_OF_BRANCHES = 1 // Default, will be changed below
var graphContent = '';
var dateContent = '';
branchNames = new Map(); // Empty list of branch names
// Add current branchName as first branch (will be to left)
let branchName = opener.window.document.getElementById('top-titlebar-branch-text').innerText;
//branchNames.set(branchName, branchNames.size);
childMap = new Map(); // List of children for commits
nodeMap = new Map(); // Map of commit nodes
mapVisibleBranchToTopCommit = new Map(); // Map of branchName to commit hash of first commit on branch (used for clickable branch names)
mapTopCommitToBranchName = new Map(); // Map of hash (of first commit on hidden branch) to branchName
commitArray = [];
columnOccupiedStateArray = [];
let previousDate = 'dummy'
// Initiate drawing
// Define arcs used for branch and merge curves
const arc = draw.defs().path(`M ${R} 0 A ${R} ${R} 0 0 1 0 ${R}`)
.fill('none')
.stroke(STROKE);
const arcBranch = draw.defs().use(arc).move(-R,-R);
const arcBranch2 = draw.defs().use(arc).flip('x').move(-R,-R);
const arcMerge = draw.defs().use(arc).flip('y').move(-R,-R);
const arcMerge2 = draw.defs().use(arc).flip('both').move(-R,-R);
//
// Pass 1 : Loop each row - collect commit info
//
/*
Get values from graphText (which comes from 'git log graph'), and store commits
Some values are updated in Pass 2 (parent branchName, lane, hidden and unknown status)
Commits stored two ways :
commitArray[row]
nodeMap.set( thisCommit.hash, thisCommit);
Also maps :
mapTopCommitToBranchName - used to map a hash to a branchName. Used for hidden commits
mapVisibleBranchToTopCommit - reverse, maps branch to hash. Used to create href from branch-list to top commit
For each row, the struct is populated :
thisCommit.hash - commit hash
thisCommit.parents - array of parents
thisCommit.notFoundInSearch - true is the commits reachable from pragma-git ( false if on other branch, or filtered by search)
thisCommit.message - commit message
thisCommit.decoration - commit decoration (branch HEAD, tag, etc)
thisCommit.branchName - derived from 1) Notes, 2) from decoration. Decoration wins if conflict. If hidden this ""
thisCommit.unknownBranchName - if branch name not determined ( pass 2 copies this to all in same branch)
thisCommit.hiddenBranchName - if branch is hidden ( pass 2 copies this to all in same branch)
thisCommit.y - row
*/
let line = 0;
let branchList = await opener.gitBranchList();
let localBranchList = branchList.local;
let sortedLocalBranchList = localBranchList.sort(function(a, b) {
return a.length - b.length; // sort by length (shortest first, longest last)
});
for(var row = 0; row < splitted.length; row++) {
// Disect git-log row into useful parts
[ longDate, hashInThisRow, thisRow, decoration, noteInThisRow, parents, messageBody] = splitGitLogRow( splitted[row] );
if (noteInThisRow == 'HEAD') {
noteInThisRow = "";
}
let date = longDate.substring(0,10); // Short date
console.log(row + ' -- ' + noteInThisRow + ' ' + thisRow);
// Style if commit is not in history (because of search)
let index = util.findObjectIndex( history, 'hash', hashInThisRow );
let notFoundInSearch = isNaN( index); // history shorter than full git log and branchHistory, because of search
// Add date (only print when date is different to previous)
if ( date == previousDate){
date = '';
}else{
// Keep date, and remember new date
previousDate = date;
}
dateContent += '<div class="date"><pre>' + date + '</pre></div>';
/* Record children hashes
(Allows me to go up (children) and down (parents)
So, the git parent info from each commit NODE, is transformed to a
childMap of the CHILDREN of a commit NODE
NODE CHILDREN
/ | \ git commits => \ | / childMap(NODE-hash) => array of CHILDREN-hashes
PARENTS NODE nodeMap(NODE-hash) => commit node
*/
// Make new entry for mapping from node to children (only if there are parents)
if ( parents[0] !== ""){
for (let i = 0; i < parents.length; i++){
if (childMap.has( parents[i] )){
childMap.get( parents[i] ).push( hashInThisRow) ;
}else{
childMap.set( parents[i], [ hashInThisRow ] );
}
}
}
// Store commit info & NUMBER_OF_BRANCHES (additional info will be added in PASS 2)
let thisCommit = {};
thisCommit.x = 0;
thisCommit.y = line; // Row number
thisCommit.hash = hashInThisRow;
thisCommit.parents = parents;
thisCommit.notFoundInSearch = notFoundInSearch;
thisCommit.message = thisRow;
thisCommit.decoration = decoration;
thisCommit.branchName = thisCommit.hash; // Default (hidden or unknown)
thisCommit.messageBody = messageBody;
thisCommit.date = longDate;
// DEV : Track where branch name info comes from
thisCommit.branchNameFromNote = noteInThisRow; // Remember what notes think is the branch name (not used)
thisCommit.branchNameFromDecoration = ''; // Remember what decoration think is the branch name (not used)
// Get branchName
// If stored with committed
let branchName = noteInThisRow; // ("" if not stored in a git-note)
// Branch from decoration (find longest match to existing branch name)
if (decoration !== ''){
sortedLocalBranchList.forEach(
(entry) => {
if ( entry.startsWith( 'remotes') ){
entry = entry.substr(8); // sortedLocalBranchList have long names -- remove 'remotes/'
}
if (decoration.includes(entry) ) {
branchName = entry;
}
}
)
thisCommit.branchNameFromDecoration = branchName;
}
// is topmost commit on a branch
let isTopCommit = ( ( !branchNames.has(branchName) && ( branchName !== "") ) || (row == 0) );
// Visible / hidden branch
if ( showBranch(branchName) ){
// Visible branch
thisCommit.hiddenBranchName = false;
// First time seeing branch -- register branchName to next integer number
if (isTopCommit){
mapVisibleBranchToTopCommit.set( branchName, thisCommit.hash); // BranchName -> top commit (used to link GUI branch-list href to commit)
if (showBranch(branchName)){
branchNames.set(branchName, branchNames.size); // Add to branchNames map, thus obtain an index for this branch in that map
}
}
}else{
// Hidden branch
thisCommit.hiddenBranchName = true;
}
// Top commit -> branchName (both hidden and visible branches)
if ( isTopCommit ){
mapTopCommitToBranchName.set( thisCommit.hash, branchName);
}
// mapTopCommitToBranchName.set( thisCommit.hash, branchName);
// Unknown branch ?
thisCommit.unknownBranchName = false;
if (branchName == ''){
thisCommit.unknownBranchName = true;
}
// Store
thisCommit.branchName = branchName;
thisCommit.x = branchNames.get(branchName);
// Store thisCommit (only if a commit row)
if ( hashInThisRow !== ""){
commitArray.push( thisCommit);
nodeMap.set( hashInThisRow, thisCommit);
}
line++;
} // End for
NUMBER_OF_KNOWN_BRANCHES = branchNames.size;
//let HIGHEST_LANE = 1;
let HIGHEST_LANE = 9;
nodeMap.delete(""); // Delete empty node
//
// PASS 2 : x-position + draw connections
//
/*
Definitions :
A segment goes beween a branchPoint and a mergePoint, following first-parent
* (mergePoint)
|\
| * startOfSegment on segment START when DEBUG==true
| * on segment
| * segment ends here on segment
|/
* afterEndOfSegment not on segment (branchPoint) END when DEBUG==true
First-parents afterEndOfSegment may have an unknown branch name. Lane 0 is reserved for unknown first-parent branches.
Add following fields to commit-struct created in PASS 1 :
commit.x - the lane to display the commit node