summaryrefslogtreecommitdiff
path: root/source/features/edit-readme.tsx
blob: 77ceedd630655d69137ce7d4c9a127c9026d715d (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
import React from 'dom-chef';
import select from 'select-dom';
import {PencilIcon} from '@primer/octicons-react';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';

import features from '.';
import GitHubURL from '../github-helpers/github-url';
import {isPermalink} from '../github-helpers';
import getDefaultBranch from '../github-helpers/get-default-branch';

async function init(): Promise<void | false> {
	const readmeHeader = await elementReady('#readme :is(.Box-header, .js-sticky)');

	// The button already exists on repos you can push to
	if (!readmeHeader || select.exists('[aria-label="Edit this file"]', readmeHeader)) {
		return false;
	}

	const isPermalink_ = await isPermalink();
	const filename = select('[href="#readme"]')!.textContent!.trim();
	const fileLink = select<HTMLAnchorElement>(`.js-navigation-open[title="${filename}"]`)!;

	const url = new GitHubURL(fileLink.href).assign({
		route: 'edit',
	});

	if (isPermalink_) {
		url.branch = await getDefaultBranch(); // Permalinks can't be edited
	}

	readmeHeader.append(
		<a
			href={String(url)}
			className={`${readmeHeader.matches('.js-sticky') ? 'p-2' : 'Box-btn-octicon'} btn-octicon`}
			aria-label="Edit this file"
		>
			<PencilIcon/>
		</a>,
	);
}

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