summaryrefslogtreecommitdiff
path: root/source/features/fork-source-link-same-view.tsx
blob: bf0b1605c8c982406ac8fcac608aba413becea7a (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
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '.';
import GitHubURL from '../github-helpers/github-url';
import doesFileExist from '../github-helpers/does-file-exist';
import getDefaultBranch from '../github-helpers/get-default-branch';
import {getRepo, getForkedRepo} from '../github-helpers';

const isFilePath = (): boolean => pageDetect.isSingleFile()
	|| (pageDetect.isRepoTree() && !pageDetect.isRepoRoot())
	|| pageDetect.hasFileEditor();

async function init(): Promise<void> {
	const forkedRepository = getRepo(getForkedRepo())!;
	const sameViewUrl = new GitHubURL(location.href).assign({
		user: forkedRepository.owner,
		repository: forkedRepository.name,
	});

	if (isFilePath()) {
		sameViewUrl.branch = await getDefaultBranch(forkedRepository);
	}

	if (pageDetect.isIssue() || pageDetect.isPR()) {
		sameViewUrl.assign({
			route: '',
			branch: '',
			filePath: '',
		});
	}

	if (!isFilePath() || await doesFileExist(sameViewUrl)) {
		select<HTMLAnchorElement>(`[data-hovercard-url="/${getForkedRepo()!}/hovercard"]`)!
			.pathname = sameViewUrl.pathname;
	}
}

void features.add(import.meta.url, {
	asLongAs: [
		pageDetect.isForkedRepo,
	],
	deduplicate: false,
	init,
});