summaryrefslogtreecommitdiff
path: root/source/features/follow-file-renames.tsx
blob: e5e4c331e42a48f66d770b930fa8208bb3de4bdf (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
import React from 'dom-chef';
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '.';
import * as api from '../github-helpers/api';
import GitHubURL from '../github-helpers/github-url';

interface File {
	previous_filename: string;
	filename: string;
	status: string;
}

async function findRename(lastCommitOnPage: string): Promise<File[]> {
	// API v4 doesn't support it: https://github.community/t5/GitHub-API-Development-and/What-is-the-corresponding-object-in-GraphQL-API-v4-for-patch/m-p/14502?collapse_discussion=true&filter=location&location=board:api&q=files%20changed%20commit&search_type=thread
	const {files} = await api.v3(`commits/${lastCommitOnPage}`);
	return files;
}

function init(): false | void {
	const disabledPagination = select.all('.paginate-container [disabled], .paginate-container .disabled');
	const url = new GitHubURL(location.href);
	// Clear the search from the url, so it does not get passed to the rename link.
	url.search = '';
	if (disabledPagination.length === 0 || !url.filePath) {
		return false;
	}

	disabledPagination.forEach(async button => {
		const isNewer = button.textContent === 'Newer';

		const fromKey = isNewer ? 'previous_filename' : 'filename';
		const toKey = isNewer ? 'filename' : 'previous_filename';
		const sha = (isNewer ? select : select.last)([
			'.commit .sha', // Pre "Repository refresh" layout
			'[aria-label="Copy the full SHA"] + a'
		])!;

		const files = await findRename(sha.textContent!.trim());

		for (const file of files) {
			if (file[fromKey] === url.filePath) {
				if (file.status === 'renamed') {
					url.assign({
						route: 'commits',
						filePath: file[toKey]
					});
					button.replaceWith(
						<a
							href={String(url)}
							aria-label={`Renamed ${isNewer ? 'to' : 'from'} ${file[toKey]}`}
							className="btn btn-outline BtnGroup-item tooltipped tooltipped-n tooltipped-no-delay"
						>
							{button.textContent}
						</a>
					);
				}

				return;
			}
		}
	});
}

void features.add(__filebasename, {
	include: [
		pageDetect.isRepoCommitList
	],
	init
});