forked from nicoespeon/gitgraph.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitgraph.ts
More file actions
486 lines (433 loc) · 14.5 KB
/
gitgraph.ts
File metadata and controls
486 lines (433 loc) · 14.5 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
import { Branch, DELETED_BRANCH_NAME, createDeletedBranch } from "./branch";
import { Commit } from "./commit";
import { createGraphRows, GraphRows } from "./graph-rows";
import { Mode } from "./mode";
import { BranchesOrder, CompareBranchesOrder } from "./branches-order";
import {
Template,
TemplateOptions,
TemplateName,
getTemplate,
} from "./template";
import { Refs } from "./refs";
import { BranchesPathsCalculator, BranchesPaths } from "./branches-paths";
import { booleanOptionOr, numberOptionOr } from "./utils";
import { Orientation } from "./orientation";
import {
GitgraphUserApi,
GitgraphBranchOptions,
GitgraphTagOptions,
} from "./user-api/gitgraph-user-api";
export { GitgraphOptions, RenderedData, GitgraphCore };
interface GitgraphOptions {
template?: TemplateName | Template;
orientation?: Orientation;
reverseArrow?: boolean;
initCommitOffsetX?: number;
initCommitOffsetY?: number;
mode?: Mode;
author?: string;
branchLabelOnEveryCommit?: boolean;
commitMessage?: string;
generateCommitHash?: () => Commit["hash"];
compareBranchesOrder?: CompareBranchesOrder;
}
interface RenderedData<TNode> {
commits: Array<Commit<TNode>>;
branchesPaths: BranchesPaths<TNode>;
commitMessagesX: number;
}
class GitgraphCore<TNode = SVGElement> {
public orientation?: Orientation;
public get isHorizontal(): boolean {
return (
this.orientation === Orientation.Horizontal ||
this.orientation === Orientation.HorizontalReverse
);
}
public get isVertical(): boolean {
return !this.isHorizontal;
}
public get isReverse(): boolean {
return (
this.orientation === Orientation.HorizontalReverse ||
this.orientation === Orientation.VerticalReverse
);
}
public get shouldDisplayCommitMessage(): boolean {
return !this.isHorizontal && this.mode !== Mode.Compact;
}
public reverseArrow: boolean;
public initCommitOffsetX: number;
public initCommitOffsetY: number;
public mode?: Mode;
public author: string;
public commitMessage: string;
public generateCommitHash: () => Commit["hash"] | undefined;
public branchesOrderFunction: CompareBranchesOrder | undefined;
public template: Template;
public branchLabelOnEveryCommit: boolean;
public refs = new Refs();
public tags = new Refs();
public tagStyles: { [name: string]: TemplateOptions["tag"] } = {};
public tagRenders: {
[name: string]: GitgraphTagOptions<TNode>["render"];
} = {};
public commits: Array<Commit<TNode>> = [];
public branches: Map<Branch["name"], Branch<TNode>> = new Map();
public currentBranch: Branch<TNode>;
private listeners: Array<(data: RenderedData<TNode>) => void> = [];
private nextTimeoutId: number | null = null;
constructor(options: GitgraphOptions = {}) {
this.template = getTemplate(options.template);
// Set a default `master` branch
this.currentBranch = this.createBranch("master");
// Set all options with default values
this.orientation = options.orientation;
this.reverseArrow = booleanOptionOr(options.reverseArrow, false);
this.initCommitOffsetX = numberOptionOr(options.initCommitOffsetX, 0);
this.initCommitOffsetY = numberOptionOr(options.initCommitOffsetY, 0);
this.mode = options.mode;
this.author = options.author || "Sergio Flores <saxo-guy@epic.com>";
this.commitMessage =
options.commitMessage || "He doesn't like George Michael! Boooo!";
this.generateCommitHash =
typeof options.generateCommitHash === "function"
? options.generateCommitHash
: () => undefined;
this.branchesOrderFunction =
typeof options.compareBranchesOrder === "function"
? options.compareBranchesOrder
: undefined;
this.branchLabelOnEveryCommit = booleanOptionOr(
options.branchLabelOnEveryCommit,
false,
);
}
/**
* Return the API to manipulate Gitgraph as a user.
* Rendering library should give that API to their consumer.
*/
public getUserApi(): GitgraphUserApi<TNode> {
return new GitgraphUserApi(this, () => this.next());
}
/**
* Add a change listener.
* It will be called any time the graph have changed (commit, merge…).
*
* @param listener A callback to be invoked on every change.
* @returns A function to remove this change listener.
*/
public subscribe(listener: (data: RenderedData<TNode>) => void): () => void {
this.listeners.push(listener);
let isSubscribed = true;
return () => {
if (!isSubscribed) return;
isSubscribed = false;
const index = this.listeners.indexOf(listener);
this.listeners.splice(index, 1);
};
}
/**
* Return all data required for rendering.
* Rendering libraries will use this to implement their rendering strategy.
*/
public getRenderedData(): RenderedData<TNode> {
const commits = this.computeRenderedCommits();
const branchesPaths = this.computeRenderedBranchesPaths(commits);
const commitMessagesX = this.computeCommitMessagesX(branchesPaths);
this.computeBranchesColor(commits, branchesPaths);
return { commits, branchesPaths, commitMessagesX };
}
/**
* Create a new branch.
*
* @param options Options of the branch
*/
public createBranch(options: GitgraphBranchOptions<TNode>): Branch<TNode>;
/**
* Create a new branch. (as `git branch`)
*
* @param name Name of the created branch
*/
public createBranch(name: string): Branch<TNode>;
public createBranch(args: any): Branch<TNode> {
const defaultParentBranchName = "HEAD";
let options = {
gitgraph: this,
name: "",
parentCommitHash: this.refs.getCommit(defaultParentBranchName),
style: this.template.branch,
onGraphUpdate: () => this.next(),
};
if (typeof args === "string") {
options.name = args;
options.parentCommitHash = this.refs.getCommit(defaultParentBranchName);
} else {
const parentBranchName = args.from
? args.from.name
: defaultParentBranchName;
const parentCommitHash =
this.refs.getCommit(parentBranchName) ||
(this.refs.hasCommit(args.from) ? args.from : undefined);
args.style = args.style || {};
options = {
...options,
...args,
parentCommitHash,
style: {
...options.style,
...args.style,
label: {
...options.style.label,
...args.style.label,
},
},
};
}
const branch = new Branch<TNode>(options);
this.branches.set(branch.name, branch);
return branch;
}
/**
* Return commits with data for rendering.
*/
private computeRenderedCommits(): Array<Commit<TNode>> {
const branches = this.getBranches();
// Commits that are not associated to a branch in `branches`
// were in a deleted branch. If the latter was merged beforehand
// they are reachable and are rendered. Others are not
const reachableUnassociatedCommits = (() => {
const unassociatedCommits = new Set(
this.commits.reduce(
(commits: Commit["hash"][], { hash }: { hash: Commit["hash"] }) =>
!branches.has(hash) ? [...commits, hash] : commits,
[],
),
);
const tipsOfMergedBranches = this.commits.reduce(
(tipsOfMergedBranches: Commit<TNode>[], commit: Commit<TNode>) =>
commit.parents.length > 1
? [
...tipsOfMergedBranches,
...commit.parents
.slice(1)
.map(
(parentHash) =>
this.commits.find(({ hash }) => parentHash === hash)!,
),
]
: tipsOfMergedBranches,
[],
);
const reachableCommits = new Set();
tipsOfMergedBranches.forEach((tip) => {
let currentCommit: Commit<TNode> | undefined = tip;
while (currentCommit && unassociatedCommits.has(currentCommit.hash)) {
reachableCommits.add(currentCommit.hash);
currentCommit =
currentCommit.parents.length > 0
? this.commits.find(
({ hash }) => currentCommit!.parents[0] === hash,
)
: undefined;
}
});
return reachableCommits;
})();
const commitsToRender = this.commits.filter(
({ hash }) =>
branches.has(hash) || reachableUnassociatedCommits.has(hash),
);
const commitsWithBranches = commitsToRender.map((commit) =>
this.withBranches(branches, commit),
);
const rows = createGraphRows(this.mode, commitsToRender);
const branchesOrder = new BranchesOrder<TNode>(
commitsWithBranches,
this.template.colors,
this.branchesOrderFunction,
);
return (
commitsWithBranches
.map((commit) => commit.setRefs(this.refs))
.map((commit) => this.withPosition(rows, branchesOrder, commit))
// Fallback commit computed color on branch color.
.map((commit) =>
commit.withDefaultColor(
this.getBranchDefaultColor(branchesOrder, commit.branchToDisplay),
),
)
// Tags need commit style to be computed (with default color).
.map((commit) =>
commit.setTags(
this.tags,
(name) =>
Object.assign({}, this.tagStyles[name], this.template.tag),
(name) => this.tagRenders[name],
),
)
);
}
/**
* Return branches paths with all data required for rendering.
*
* @param commits List of commits with rendering data computed
*/
private computeRenderedBranchesPaths(
commits: Array<Commit<TNode>>,
): BranchesPaths<TNode> {
return new BranchesPathsCalculator<TNode>(
commits,
this.branches,
this.template.commit.spacing,
this.isVertical,
this.isReverse,
() => createDeletedBranch(this, this.template.branch, () => this.next()),
).execute();
}
/**
* Set branches colors based on branches paths.
*
* @param commits List of graph commits
* @param branchesPaths Branches paths to be rendered
*/
private computeBranchesColor(
commits: Array<Commit<TNode>>,
branchesPaths: BranchesPaths<TNode>,
): void {
const branchesOrder = new BranchesOrder<TNode>(
commits,
this.template.colors,
this.branchesOrderFunction,
);
Array.from(branchesPaths).forEach(([branch]) => {
branch.computedColor =
branch.style.color ||
this.getBranchDefaultColor(branchesOrder, branch.name);
});
}
/**
* Return commit messages X position for rendering.
*
* @param branchesPaths Branches paths to be rendered
*/
private computeCommitMessagesX(branchesPaths: BranchesPaths<TNode>): number {
const numberOfColumns = Array.from(branchesPaths).length;
return numberOfColumns * this.template.branch.spacing;
}
/**
* Add `branches` property to commit.
*
* @param branches All branches mapped by commit hash
* @param commit Commit
*/
private withBranches(
branches: Map<Commit["hash"], Set<Branch["name"]>>,
commit: Commit<TNode>,
): Commit<TNode> {
let commitBranches = Array.from(
(branches.get(commit.hash) || new Set()).values(),
);
if (commitBranches.length === 0) {
// No branch => branch has been deleted.
commitBranches = [DELETED_BRANCH_NAME];
}
return commit.setBranches(commitBranches);
}
/**
* Get all branches from current commits.
*/
private getBranches(): Map<Commit["hash"], Set<Branch["name"]>> {
const result = new Map<Commit["hash"], Set<Branch["name"]>>();
const queue: Array<Commit["hash"]> = [];
const branches = this.refs.getAllNames().filter((name) => name !== "HEAD");
branches.forEach((branch) => {
const commitHash = this.refs.getCommit(branch);
if (commitHash) {
queue.push(commitHash);
}
while (queue.length > 0) {
const currentHash = queue.pop() as Commit["hash"];
const current = this.commits.find(
({ hash }) => hash === currentHash,
) as Commit<TNode> | null;
const prevBranches =
result.get(currentHash) || new Set<Branch["name"]>();
prevBranches.add(branch);
result.set(currentHash, prevBranches);
if (current && current.parents && current.parents.length > 0) {
queue.push(current.parents[0]);
}
}
});
return result;
}
/**
* Add position to given commit.
*
* @param rows Graph rows
* @param branchesOrder Computed order of branches
* @param commit Commit to position
*/
private withPosition(
rows: GraphRows<TNode>,
branchesOrder: BranchesOrder<TNode>,
commit: Commit<TNode>,
): Commit<TNode> {
const row = rows.getRowOf(commit.hash);
const maxRow = rows.getMaxRow();
const order = branchesOrder.get(commit.branchToDisplay);
switch (this.orientation) {
default:
return commit.setPosition({
x: this.initCommitOffsetX + this.template.branch.spacing * order,
y:
this.initCommitOffsetY +
this.template.commit.spacing * (maxRow - row),
});
case Orientation.VerticalReverse:
return commit.setPosition({
x: this.initCommitOffsetX + this.template.branch.spacing * order,
y: this.initCommitOffsetY + this.template.commit.spacing * row,
});
case Orientation.Horizontal:
return commit.setPosition({
x: this.initCommitOffsetX + this.template.commit.spacing * row,
y: this.initCommitOffsetY + this.template.branch.spacing * order,
});
case Orientation.HorizontalReverse:
return commit.setPosition({
x:
this.initCommitOffsetX +
this.template.commit.spacing * (maxRow - row),
y: this.initCommitOffsetY + this.template.branch.spacing * order,
});
}
}
/**
* Return the default color for given branch.
*
* @param branchesOrder Computed order of branches
* @param branchName Name of the branch
*/
private getBranchDefaultColor(
branchesOrder: BranchesOrder<TNode>,
branchName: Branch["name"],
): string {
return branchesOrder.getColorOf(branchName);
}
/**
* Tell each listener something new happened.
* E.g. a rendering library will know it needs to re-render the graph.
*/
private next() {
if (this.nextTimeoutId) {
window.clearTimeout(this.nextTimeoutId);
}
// Use setTimeout() with `0` to debounce call to next tick.
this.nextTimeoutId = window.setTimeout(() => {
this.listeners.forEach((listener) => listener(this.getRenderedData()));
}, 0);
}
}