forked from yusuf8834/bb-git-history
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.ts
More file actions
89 lines (74 loc) · 2.31 KB
/
Copy pathgraph.ts
File metadata and controls
89 lines (74 loc) · 2.31 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
import type { GitCommitSummary } from "./contracts";
export interface GraphEdge {
fromLane: number;
toLane: number;
kind: "straight" | "merge";
}
export interface GraphRow {
commitLane: number;
laneCount: number;
topLanes: number[];
bottomLanes: number[];
edges: GraphEdge[];
startsHere: boolean;
}
function firstOpenLane(lanes: Array<string | null>): number {
const open = lanes.indexOf(null);
if (open >= 0) return open;
lanes.push(null);
return lanes.length - 1;
}
/**
* Assign stable lanes to commits in Git's topological, newest-first order.
* The output contains only drawing instructions, so the React view can
* virtualize rows without keeping layout state in mounted components.
*/
export function layoutCommitGraph(commits: GitCommitSummary[]): GraphRow[] {
const lanes: Array<string | null> = [];
const rows: GraphRow[] = [];
for (const commit of commits) {
let commitLane = lanes.indexOf(commit.hash);
const startsHere = commitLane < 0;
if (startsHere) {
commitLane = firstOpenLane(lanes);
lanes[commitLane] = commit.hash;
}
const topLanes = lanes
.map((value, lane) => (value === null ? -1 : lane))
.filter((lane) => lane >= 0 && lane !== commitLane);
const edges: GraphEdge[] = [];
const next = [...lanes];
next[commitLane] = null;
commit.parents.forEach((parentHash, parentIndex) => {
let targetLane = next.indexOf(parentHash);
if (targetLane < 0) {
if (parentIndex === 0 && next[commitLane] === null) {
targetLane = commitLane;
} else {
targetLane = firstOpenLane(next);
}
next[targetLane] = parentHash;
}
edges.push({
fromLane: commitLane,
toLane: targetLane,
kind: targetLane === commitLane ? "straight" : "merge",
});
});
while (next.length > 0 && next.at(-1) === null) next.pop();
const bottomLanes = next
.map((value, lane) => (value === null ? -1 : lane))
.filter((lane) => lane >= 0 && !edges.some((edge) => edge.toLane === lane));
const laneCount = Math.max(lanes.length, next.length, commitLane + 1);
rows.push({
commitLane,
laneCount,
topLanes,
bottomLanes,
edges,
startsHere,
});
lanes.splice(0, lanes.length, ...next);
}
return rows;
}