summaryrefslogtreecommitdiff
path: root/source/features/pinned-issues-update-time.tsx
blob: cfce877773ff9e1eda5851be52668a21b4d2ae3c (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
import React from 'dom-chef';
import {CachedFunction} from 'webext-storage-cache';
import {$} from 'select-dom';
import batchedFunction from 'batched-function';
import * as pageDetect from 'github-url-detection';

import features from '../feature-manager.js';
import api from '../github-helpers/api.js';
import {getRepo} from '../github-helpers/index.js';
import looseParseInt from '../helpers/loose-parse-int.js';
import observe from '../helpers/selector-observer.js';

type IssueInfo = {
	updatedAt: string;
};

const getLastUpdated = new CachedFunction('last-updated', {
	async updater(issueNumbers: number[]): Promise<Record<string, IssueInfo>> {
		const {repository} = await api.v4(`
		repository() {
			${issueNumbers.map(number => `
				${api.escapeKey(number)}: issue(number: ${number}) {
					updatedAt
				}
			`).join('\n')}
		}
	`);

		return repository;
	},
	maxAge: {minutes: 30},
	cacheKey: ([issues]) => `${getRepo()!.nameWithOwner}:${String(issues)}`,
});

function getPinnedIssueNumber(pinnedIssue: HTMLElement): number {
	return looseParseInt($('.opened-by', pinnedIssue)!.firstChild!);
}

async function update(pinnedIssues: HTMLElement[]): Promise<void> {
	const lastUpdated: Record<string, IssueInfo> = await getLastUpdated.get(pinnedIssues.map(issue => getPinnedIssueNumber(issue)));
	for (const pinnedIssue of pinnedIssues) {
		const issueNumber = getPinnedIssueNumber(pinnedIssue);
		const {updatedAt} = lastUpdated[api.escapeKey(issueNumber)];
		const originalLine = $('.opened-by', pinnedIssue)!;
		originalLine.after(
			// .rgh class enables tweakers to hide the number
			<span className="text-small color-fg-muted">
				<span className="rgh-pinned-issue-number">#{issueNumber}</span> updated <relative-time datetime={updatedAt}/>
			</span>,
		);

		originalLine.hidden = true;
	}
}

async function init(signal: AbortSignal): Promise<void> {
	observe('.pinned-issue-item', batchedFunction(update, {delay: 100}), {signal});
}

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

/*

Test URLs:

https://github.com/refined-github/refined-github/issues

*/