summaryrefslogtreecommitdiff
path: root/source/features/link-to-file-in-file-history.tsx
blob: 998a57cc867dd3abe62926b84778cb42455fd218 (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
/**
Adds direct link to file/directory when viewing the history.
See it in action at https://github.com/sindresorhus/refined-github/commits/master/readme.md
*/

import React from 'dom-chef';
import select from 'select-dom';
import features from '../libs/features';
import {file} from '../libs/icons';
import {getRepoPath} from '../libs/utils';
import {groupSiblings} from '../libs/group-buttons';

function init(): void | false {
	// /user/repo/commits/master/readme.md -> 'readme.md'
	// /user/repo/commits/master/          -> ''
	const path = getRepoPath()!.replace(/^commits\/[^/]+\/?/, '');
	if (!path) {
		return false;
	}

	for (const rootLink of select.all<HTMLAnchorElement>('[aria-label="Browse the repository at this point in the history"]')) {
		// `rootLink.pathname` points to /tree/ but GitHub automatically redirects to /blob/ when the path is of a file
		rootLink.before(
			<a
				href={rootLink.pathname + '/' + path}
				className="btn btn-outline tooltipped tooltipped-sw"
				aria-label="See object at this point in the history"
			>
				{file()}
			</a>
		);

		// TODO: drop `as` after https://github.com/Microsoft/TSJS-lib-generator/pull/697
		(rootLink.closest('.commit-links-cell') as HTMLElement).style.width = 'auto';

		groupSiblings(rootLink);
	}
}

features.add({
	id: 'link-to-file-in-file-history',
	include: [
		features.isCommitList
	],
	load: features.onAjaxedPages,
	init
});