summaryrefslogtreecommitdiff
path: root/source/features/rgh-improve-new-issue-form.tsx
blob: 7fd42bb012efa4c57d9b16c0c0cd57234e3c55a7 (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
import React from 'dom-chef';
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '../feature-manager.js';
import openOptions from '../helpers/open-options.js';
import clearCacheHandler from '../helpers/clear-cache-handler.js';
import {expectToken, expectTokenScope} from '../github-helpers/api.js';
import {isRefinedGitHubRepo} from '../github-helpers/index.js';

function addNotice(adjective: JSX.Element | string): void {
	select('#issue_body_template_name')!.before(
		<div className="flash flash-warn m-2">
			Your Personal Access Token is {adjective}. Some Refined GitHub features will not work without it.
			You can update it <button className="btn-link" type="button" onClick={openOptions as unknown as React.MouseEventHandler}>in the options</button>.
		</div>,
	);
}

async function checkToken(): Promise<void> {
	try {
		await expectToken();
	} catch {
		addNotice('missing');
		return;
	}

	try {
		await expectTokenScope('repo');
	} catch {
		addNotice('invalid or expired');
	}
}

async function setVersion(): Promise<void> {
	const {version} = browser.runtime.getManifest();
	select('input#issue_form_version')!.value = version;
}

async function linkifyCacheRefresh(): Promise<void> {
	select('[href="#clear-cache"]')!.replaceWith(
		<button
			className="btn"
			type="button"
			onClick={clearCacheHandler as unknown as React.MouseEventHandler}
		>
			Clear cache
		</button>,
	);
}

async function init(): Promise<void> {
	// Async functions so they're independent
	await Promise.all([
		linkifyCacheRefresh(),
		checkToken(),
		setVersion(),
	]);
}

void features.add(import.meta.url, {
	asLongAs: [
		isRefinedGitHubRepo,
		pageDetect.isNewIssue,
		() => new URL(location.href).searchParams.get('template') === '1_bug_report.yml',
	],
	awaitDomReady: true, // Small page
	deduplicate: 'has-rgh-inner',
	init,
});