summaryrefslogtreecommitdiff
path: root/source/features/default-branch-button.tsx
blob: 866f80c8fb246aa72aa46c3c668bc2bcd94b7853 (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
import './default-branch-button.css';
import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import {ChevronLeftIcon} from '@primer/octicons-react';

import features from '../feature-manager.js';
import GitHubURL from '../github-helpers/github-url.js';
import {groupButtons} from '../github-helpers/group-buttons.js';
import getDefaultBranch from '../github-helpers/get-default-branch.js';
import observe from '../helpers/selector-observer.js';
import {branchSelector} from '../github-helpers/selectors.js';
import isDefaultBranch from '../github-helpers/is-default-branch.js';
import {isRepoCommitListRoot} from '../github-helpers/index.js';

async function add(branchSelector: HTMLElement): Promise<void> {
	// Don't show the button if we’re already on the default branch
	// TODO: Move to `asLongAs` when it accepts async detections
	if (await isDefaultBranch()) {
		return;
	}

	const url = new GitHubURL(location.href);
	if (pageDetect.isRepoRoot()) {
		// The default branch of the root directory is just /user/repo/
		url.route = '';
		url.branch = '';
	} else {
		url.branch = await getDefaultBranch();
	}

	const defaultLink = (
		<a
			className="btn tooltipped tooltipped-ne px-2"
			href={url.href}
			data-turbo-frame="repo-content-turbo-frame"
			aria-label="See this view on the default branch"
		>
			<ChevronLeftIcon/>
		</a>
	);

	// The DOM varies between details-based DOM and React-based one
	const selectorWrapper = branchSelector.tagName === 'SUMMARY'
		? branchSelector.parentElement!
		: branchSelector;

	selectorWrapper.before(defaultLink);
	groupButtons([defaultLink, selectorWrapper]).classList.add('d-flex', 'rgh-default-branch-button-group');
}

function init(signal: AbortSignal): void {
	observe(branchSelector, add, {signal});
}

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