-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.ts
More file actions
273 lines (230 loc) · 9.1 KB
/
script.ts
File metadata and controls
273 lines (230 loc) · 9.1 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
const REPO_HISTORY_KEY = 'githubRandomIssueRepos';
const MAX_HISTORY = 5;
interface GitHubIssue {
state: string;
number: number;
title: string;
html_url: string;
labels: Array<{
name: string;
color?: string;
[key: string]: any;
}>;
pull_request?: {
url: string;
};
}
const fetchButton = document.getElementById('fetch-issue') as HTMLButtonElement;
const clearButton = document.getElementById('clear-output') as HTMLButtonElement;
const outputDiv = document.getElementById('output') as HTMLDivElement;
const repoInput = document.getElementById('repo-input') as HTMLInputElement;
const totalCount = document.getElementById('total-count') as HTMLSpanElement;
const prsCount = document.getElementById('prs-count') as HTMLSpanElement;
const issuesCount = document.getElementById('issues-count') as HTMLSpanElement;
const openIssuesCount = document.getElementById('open-issues-count') as HTMLSpanElement;
const staleCount = document.getElementById('stale-count') as HTMLSpanElement;
let entryCount = 0; // Counter to track the number of entries
let prevIssue = -1;
let optionKeyHeld = false;
let allIssuesGlobal: GitHubIssue[] = [];
function setLoadingState(isLoading: boolean) {
const container = document.getElementById('button-container');
const repoInput = document.getElementById('repo-input') as HTMLInputElement;
if (isLoading) {
container?.classList.add('disabled');
repoInput.disabled = true;
} else {
container?.classList.remove('disabled');
repoInput.disabled = false;
}
}
function updateStatusFields(issues: GitHubIssue[]) {
const total = issues.length;
const prs = issues.filter(issue => issue.pull_request).length;
const allIssues = issues.filter(issue => !issue.pull_request).length;
const openIssues = issues.filter(issue => !issue.pull_request && issue.state === 'open').length;
const staleIssues = issues.filter(issue =>
!issue.pull_request &&
issue.labels.some(label => label.name.toLowerCase() === 'stale')
).length;
totalCount.textContent = `Total: ${total}`;
prsCount.textContent = `PRs: ${prs}`;
issuesCount.textContent = `Issues: ${allIssues}`;
openIssuesCount.textContent = `Open: ${openIssues}`;
staleCount.textContent = `Stale: ${staleIssues}`;
if (staleIssues > 0) {
const firstStaleIssueColor = issues.find(issue =>
!issue.pull_request &&
issue.labels.some(label => label.name.toLowerCase() === 'stale')
)?.labels.find(label => label.name.toLowerCase() === 'stale')?.color;
if (firstStaleIssueColor) {
staleCount.style.color = `#${firstStaleIssueColor}`;
}
staleCount.style.display = 'block';
} else {
staleCount.style.display = 'none';
}
}
function decodeHTMLEntities(text: string): string {
const textarea = document.createElement('textarea');
textarea.innerHTML = text;
return textarea.value;
}
function appendOutput(title: string, issueNumber?: number, url?: string, debug?: boolean) {
const newOutput = document.createElement('div');
const link = document.createElement('a');
if (url) {
link.href = url;
link.target = '_blank';
link.style.color = 'inherit';
link.style.textDecoration = 'none';
}
const prefix = issueNumber !== undefined ? `#${issueNumber} - ` : '';
const decodedTitle = decodeHTMLEntities(title);
link.textContent = prefix + decodedTitle;
newOutput.appendChild(link);
// Alternate background colour for every second entry
if (entryCount % 2 === 1) {
newOutput.style.backgroundColor = '#f9f9f9'; // Light grey for even entries
}
// Only show debug messages if Option key is held down
if (debug && !optionKeyHeld) return;
// Show debug messages in red
if (debug) {
newOutput.style.color = 'red';
}
outputDiv.appendChild(newOutput);
entryCount++; // Increment the counter
// Scroll the output to the bottom
outputDiv.scrollTop = outputDiv.scrollHeight;
}
async function fetchGitHubIssues(repo: string): Promise<GitHubIssue[]> {
appendOutput('fetchGitHubIssues()', undefined, undefined, true)
if (allIssuesGlobal.length > 0) {
appendOutput('Using cached issues.', undefined, undefined, true);
return allIssuesGlobal;
}
appendOutput('Fetching issues...', undefined, undefined, true);
let url = new URL('https://api.github.com');
url.pathname = `/repos/${repo}/issues`;
url.searchParams.set('per_page', '100');
url.searchParams.set('page', '1');
url.searchParams.set('state', 'all'); // open, closed, or all
let allIssues: GitHubIssue[] = [];
let currentPage = 1;
while (true) {
appendOutput(`Fetching page ${currentPage}...`, undefined, undefined, true);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch issues (page ${currentPage}): ${response.statusText}`);
}
const issues = await response.json() as GitHubIssue[];
appendOutput(`Fetched page ${currentPage}, ${issues.length} more issues...`, undefined, undefined, true);
allIssues = [...allIssues, ...issues];
updateStatusFields(allIssues);
const linkHeader = response.headers.get('Link');
const nextLink = linkHeader?.match(/<(.*)>; rel="next"/)?.[1];
if (!nextLink) {
break;
}
appendOutput(`Next link: ${nextLink}...`, undefined, undefined, true);
url = new URL(nextLink);
currentPage++;
}
allIssuesGlobal = allIssues;
return allIssues;
}
async function getRandomIssue(repo: string): Promise<void> {
if (!repo.includes('/')) {
appendOutput('Invalid repository format. Use "owner/repo".', undefined, undefined);
return;
}
setLoadingState(true);
fetchButton.disabled = true;
try {
const allIssues = await fetchGitHubIssues(repo);
const openIssues = allIssues.filter((issue: GitHubIssue) => !issue.pull_request && issue.state === 'open');
if (openIssues.length === 0) {
appendOutput('No issues found.', undefined, undefined);
} else {
// Try three times in case we chose the same issue twice in a row
for (let i = 0; i < 3; i++) {
const randomIssue = openIssues[Math.floor(Math.random() * openIssues.length)];
if (randomIssue.number !== prevIssue) {
appendOutput(randomIssue.title, randomIssue.number, randomIssue.html_url);
prevIssue = randomIssue.number;
break;
}
}
}
} catch (error) {
if (error instanceof Error) {
appendOutput(`Error fetching issues: ${error.message}`, undefined, undefined);
} else {
appendOutput('Unknown error occurred.', undefined, undefined);
}
} finally {
setLoadingState(false);
fetchButton.disabled = false;
// Wait for the animation to finish before removing the spin class
setTimeout(() => {
fetchButton.classList.remove('spin'); // Remove spin class to stop spinning
}, 1000); // Match this duration to the CSS animation duration (1s)
}
}
function handleFetchClick() {
const repo = repoInput.value.trim();
if (repo) {
saveToRepoHistory(repo);
fetchButton.classList.add('spin');
getRandomIssue(repo);
} else {
appendOutput('Please enter a repository name.', undefined, undefined);
}
}
function handleClearClick() {
outputDiv.innerHTML = '';
}
function saveToRepoHistory(repo: string) {
let history = JSON.parse(localStorage.getItem(REPO_HISTORY_KEY) || '[]');
// Remove if exists and add to beginning
history = [repo, ...history.filter((r: string) => r !== repo)].slice(0, MAX_HISTORY);
localStorage.setItem(REPO_HISTORY_KEY, JSON.stringify(history));
updateRepoHistory(history);
}
function updateRepoHistory(history: string[]) {
const datalist = document.getElementById('repo-history');
if (datalist) {
datalist.innerHTML = history
.map(repo => `<option value="${repo}">${repo}</option>`)
.join('');
}
}
function initialize() {
if (fetchButton && outputDiv && repoInput) {
fetchButton.addEventListener('click', handleFetchClick);
}
if (clearButton && outputDiv) {
clearButton.addEventListener('click', handleClearClick);
}
// Option key listeners
window.addEventListener('keydown', (e) => {
if (e.key === 'Alt' || e.key === 'Option') {
optionKeyHeld = true;
}
});
window.addEventListener('keyup', (e) => {
if (e.key === 'Alt' || e.key === 'Option') {
optionKeyHeld = false;
}
});
repoInput?.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
handleFetchClick();
}
});
const savedHistory = JSON.parse(localStorage.getItem(REPO_HISTORY_KEY) || '[]');
updateRepoHistory(savedHistory);
}
// Start the app
initialize();