summaryrefslogtreecommitdiff
path: root/source/features/profile-gists-link.tsx
blob: b755190e8ec019ff160c2e21d2a9e54d4c9f8f56 (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
71
72
73
74
75
76
import React from 'dom-chef';
import cache from 'webext-storage-cache';
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';
import {CodeSquareIcon} from '@primer/octicons-react';

import features from '../feature-manager.js';
import * as api from '../github-helpers/api.js';
import {getCleanPathname} from '../github-helpers/index.js';
import createDropdownItem from '../github-helpers/create-dropdown-item.js';
import observe from '../helpers/selector-observer.js';

const getGistCount = cache.function('gist-count', async (username: string): Promise<number> => {
	const {user} = await api.v4(`
		user(login: "${username}") {
			gists(first: 0) {
				totalCount
			}
		}
	`);
	return user.gists.totalCount;
}, {
	maxAge: {days: 1},
	staleWhileRevalidate: {days: 3},
});

function getUser(): {url: string; name: string} {
	const name = getCleanPathname();
	const url = pageDetect.isEnterprise()
		? `/gist/${name}`
		: `https://gist.github.com/${name}`;
	return {url, name};
}

async function appendTab(navigationBar: Element): Promise<void> {
	const user = getUser();
	const link = (
		<a
			href={user.url}
			className="UnderlineNav-item js-responsive-underlinenav-item"
			role="tab"
			aria-selected="false"
			data-tab-item="rgh-gists-item"
		>
			<CodeSquareIcon className="UnderlineNav-octicon hide-sm"/>
			{' Gists '}
		</a>
	);

	navigationBar.append(link);
	navigationBar.replaceWith(navigationBar);

	// There are two UnderlineNav items (responsive…) that point to the same dropdown
	const overflowNav = select('.js-responsive-underlinenav .dropdown-menu ul')!;
	if (!select.exists('[data-rgh-label="Gists"]', overflowNav)) {
		overflowNav.append(
			createDropdownItem('Gists', user.url),
		);
	}

	const count = await getGistCount(user.name);
	if (count > 0) {
		link.append(<span className="Counter">{count}</span>);
	}
}

async function init(signal: AbortSignal): Promise<void> {
	observe('nav[aria-label="User profile"]', appendTab, {signal});
}

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