summaryrefslogtreecommitdiff
path: root/source/features/linkify-branch-refs.tsx
blob: 9a71134b3c95bf13b15006f4992de8a4af0b7097 (plain) (blame)
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
import React from 'dom-chef';
import select from 'select-dom';
import features from '../libs/features';
import * as pageDetect from '../libs/page-detect';
import {getOwnerAndRepo} from '../libs/utils';
import {safeElementReady, wrap} from '../libs/dom-utils';

function inPR() {
	let deletedBranch: string;
	const lastBranchAction = select.all(`
		.discussion-item-head_ref_deleted .commit-ref,
		.discussion-item-head_ref_restored .commit-ref
	`).pop();
	if (lastBranchAction && lastBranchAction.closest('.discussion-item-head_ref_deleted')) {
		deletedBranch = lastBranchAction.textContent.trim();
	}

	// Find the URLs first, some elements don't have titles
	const urls = new Map<string, string>();
	for (const el of select.all<HTMLElement>('.commit-ref[title], .base-ref[title], .head-ref[title]')) {
		const [repo, branch] = el.title.split(':');
		const branchName = el.textContent.trim();
		urls.set(
			el.textContent.trim(),
			`/${repo}`
		);
		if (branchName !== deletedBranch) {
			urls.set(
				el.textContent.trim(),
				`/${repo}/tree/${encodeURIComponent(branch)}`
			);
		}
	}

	for (const el of select.all<HTMLElement>('.commit-ref')) {
		const branchName = el.textContent.trim();

		if (branchName !== 'unknown repository') {
			if (branchName === deletedBranch) {
				el.title = 'Deleted';
				el.style.textDecoration = 'line-through';
			}

			wrap(el, <a href={urls.get(branchName)}></a>);
		}
	}
}

async function inQuickPR() {
	const el = await safeElementReady('.branch-name');
	if (el) {
		const {ownerName, repoName} = getOwnerAndRepo();
		const branchUrl = `/${ownerName}/${repoName}/tree/${el.textContent}`;
		wrap(el.closest('.branch-name'), <a href={branchUrl}></a>);
	}
}

function init() {
	if (pageDetect.isPR()) {
		inPR();
	} else if (pageDetect.isQuickPR()) {
		inQuickPR();
	}
}

features.add({
	id: 'linkify-branch-refs',
	include: [
		features.isPR,
		features.isQuickPR
	],
	load: features.onAjaxedPages,
	init
});