summaryrefslogtreecommitdiff
path: root/source/features/previous-version.tsx
blob: d1af998c56ca7a8891c5743b476638f641a96eae (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
import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import {VersionsIcon} from '@primer/octicons-react';

import features from '../feature-manager.js';
import observe from '../helpers/selector-observer.js';
import api from '../github-helpers/api.js';
import GitHubFileURL from '../github-helpers/github-file-url.js';
import previousVersionQuery from './previous-version.gql';

async function getPreviousCommitForFile(pathname: string): Promise<string | undefined> {
	const {user, repository, branch, filePath} = new GitHubFileURL(pathname);
	const {resource} = await api.v4(previousVersionQuery, {
		variables: {
			filePath,
			resource: `/${user}/${repository}/commit/${branch}`,
		},
	});

	// The first commit refers to the current one, so we skip it
	return resource.history.nodes[1]?.oid;
}

async function add(historyButton: HTMLElement): Promise<void> {
	const previousCommit = await getPreviousCommitForFile(location.href);
	if (!previousCommit) {
		return;
	}

	const url = new GitHubFileURL(location.href)
		.assign({branch: previousCommit});

	historyButton.before(
		<a href={url.href} className="UnderlineNav-item tooltipped tooltipped-n ml-2" aria-label="View previous version">
			<VersionsIcon className="UnderlineNav-octicon mr-0"/>
		</a>,
	);
}

async function init(signal: AbortSignal): Promise<void> {
	observe('a.react-last-commit-history-group', add, {signal});
}

void features.add(import.meta.url, {
	include: [
		pageDetect.isSingleFile,
	],
	exclude: [
		pageDetect.isRepoFile404,
	],
	init,
});

/*

Test URL

https://github.com/refined-github/refined-github/blob/main/readme.md

*/