-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.ts
More file actions
484 lines (409 loc) · 18.9 KB
/
script.ts
File metadata and controls
484 lines (409 loc) · 18.9 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
const REPO_HISTORY_KEY = 'githubRandomIssueRepos';
const MAX_HISTORY = 5;
// Build timestamp - update this when compiling: new Date().toISOString()
const BUILD_TIME = '2026-05-06T23:46:00.000Z';
interface GitHubIssue {
state: string;
number: number;
title: string;
html_url: string;
labels: Array<{
name: string;
color?: string;
[key: string]: any;
}>;
pull_request?: {
url: string;
html_url?: string;
merged_at?: string | null;
};
merged?: boolean | null;
merged_at?: string | null;
}
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;
const unmergedCount = document.getElementById('unmerged-count') as HTMLSpanElement;
const testModeBtn = document.getElementById('test-mode') as HTMLButtonElement;
const buildStatus = document.getElementById('build-status') as HTMLSpanElement;
const buildTimeElement = document.getElementById('build-time') as HTMLSpanElement;
let entryCount = 0; // Counter to track the number of entries
let prevIssue = -1;
let optionKeyHeld = false;
let allIssuesGlobal: GitHubIssue[] = [];
const toggleStates = {
prs: false,
issues: false
};
let testModeEnabled = false;
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 updateDiceButtonState() {
const hasActiveToggle = toggleStates.prs || toggleStates.issues;
fetchButton.disabled = !hasActiveToggle;
fetchButton.style.opacity = hasActiveToggle ? '1' : '0.4';
fetchButton.style.cursor = hasActiveToggle ? 'pointer' : 'not-allowed';
}
function handleToggleClick(type: 'prs' | 'issues') {
const oldValue = toggleStates[type];
toggleStates[type] = !toggleStates[type];
const newValue = toggleStates[type];
appendOutput(`Toggle ${type}: ${oldValue} -> ${newValue}`, undefined, undefined, true);
updateToggleButtonVisual(type);
updateDiceButtonState();
}
function updateToggleButtonVisual(type: 'prs' | 'issues') {
const element = type === 'prs' ? prsCount : issuesCount;
if (toggleStates[type]) {
element.classList.add('active');
element.classList.remove('disabled');
} else {
element.classList.remove('active');
element.classList.add('disabled');
}
}
function updateStatusFields(issues: GitHubIssue[]) {
const total = issues.length;
const allPrs = issues.filter(issue => issue.pull_request).length;
const openUnmergedPrs = issues.filter(issue =>
issue.pull_request && issue.pull_request?.merged_at === null && issue.state === 'open'
).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: ${allPrs}`;
unmergedCount.textContent = `Open: ${openUnmergedPrs}`;
issuesCount.textContent = `⚠️ Issues: ${allIssues}`;
openIssuesCount.textContent = `Open: ${openIssues}`;
staleCount.textContent = `Stale: ${staleIssues}`;
updateDiceButtonState();
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;
// In test mode, fetch 2 pages to see more data
const maxPages = testModeEnabled ? 2 : Number.POSITIVE_INFINITY;
while (currentPage <= maxPages) {
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);
// Build the pool based on toggle states
let candidatePool: GitHubIssue[] = [];
if (toggleStates.prs) {
appendOutput(`Debug: Processing PR toggle...`, undefined, undefined, true);
const allPrs = allIssues.filter(issue => issue.pull_request);
const mergedPrs = allPrs.filter(issue => issue.pull_request?.merged_at !== null);
const openUnmergedPrs = allPrs.filter(issue => issue.pull_request?.merged_at === null && issue.state === 'open');
const closedUnmergedPrs = allPrs.filter(issue => issue.pull_request?.merged_at === null && issue.state === 'closed');
appendOutput(`Debug: Found ${allPrs.length} total PRs: ${mergedPrs.length} merged, ${openUnmergedPrs.length} open unmerged, ${closedUnmergedPrs.length} closed unmerged`, undefined, undefined, true);
// Show all PRs in debug
appendOutput(`Debug: All PRs:`, undefined, undefined, true);
allPrs.forEach((pr: GitHubIssue) => {
const isMerged = pr.pull_request?.merged_at !== null;
const status = isMerged ? 'merged' : 'unmerged';
const labels = pr.labels.map((l: any) => l.name).join(', ') || 'none';
appendOutput(` 🛠️ #${pr.number} [${pr.state}, ${status}] merged_at=${pr.pull_request?.merged_at}`, undefined, undefined, true);
});
appendOutput(`Filtering: Found ${openUnmergedPrs.length} open unmerged PRs (excluding ${closedUnmergedPrs.length} closed unmerged)`, undefined, undefined, true);
if (openUnmergedPrs.length > 0) {
openUnmergedPrs.forEach((pr: GitHubIssue) => {
const labels = pr.labels.map((l: any) => l.name).join(', ') || 'none';
appendOutput(` 🛠️ #${pr.number} [${pr.state}] ${labels}`, undefined, undefined, true);
});
} else {
appendOutput(` ℹ️ No open unmerged PRs available - all PRs are merged or closed`, undefined, undefined, true);
}
candidatePool = [...candidatePool, ...openUnmergedPrs];
appendOutput(`Debug: Candidate pool size after PRs: ${candidatePool.length}`, undefined, undefined, true);
}
if (toggleStates.issues) {
appendOutput(`Debug: Processing Issues toggle...`, undefined, undefined, true);
const allIssuesOnly = allIssues.filter(issue => !issue.pull_request);
const openIssues = allIssuesOnly.filter(issue => issue.state === 'open');
const closedIssues = allIssuesOnly.filter(issue => issue.state === 'closed');
appendOutput(`Debug: Found ${allIssuesOnly.length} total issues: ${openIssues.length} open, ${closedIssues.length} closed`, undefined, undefined, true);
// Show all issues in debug
appendOutput(`Debug: All Issues:`, undefined, undefined, true);
allIssuesOnly.forEach(issue => {
const labels = issue.labels.map(l => l.name).join(', ') || 'none';
appendOutput(` ⚠️ #${issue.number} [${issue.state}] ${labels}`, undefined, undefined, true);
});
appendOutput(`Filtering: Found ${openIssues.length} open issues`, undefined, undefined, true);
if (openIssues.length > 0) {
openIssues.forEach(issue => {
const labels = issue.labels.map(l => l.name).join(', ') || 'none';
appendOutput(` ⚠️ #${issue.number} [${issue.state}] ${labels}`, undefined, undefined, true);
});
} else {
appendOutput(` ℹ️ All issues are closed - no selectable issues available`, undefined, undefined, true);
}
candidatePool = [...candidatePool, ...openIssues];
appendOutput(`Debug: Candidate pool size after Issues: ${candidatePool.length}`, undefined, undefined, true);
}
appendOutput(`Debug: Final candidate pool size: ${candidatePool.length}`, undefined, undefined, true);
if (candidatePool.length === 0) {
appendOutput('No items found for selected type(s).', undefined, undefined);
if (optionKeyHeld) {
appendOutput(`Debug: PRs toggle: ${toggleStates.prs}, Issues toggle: ${toggleStates.issues}`, undefined, undefined, true);
appendOutput('Debug: Make sure at least one toggle button is active (green)', undefined, undefined, true);
}
} else {
// Try three times in case we chose the same issue twice in a row
for (let i = 0; i < 3; i++) {
const randomItem = candidatePool[Math.floor(Math.random() * candidatePool.length)];
if (randomItem.number !== prevIssue) {
const emoji = randomItem.pull_request ? '🛠️' : '⚠️';
const titleWithEmoji = `${emoji} ${randomItem.title}`;
appendOutput(titleWithEmoji, randomItem.number, randomItem.html_url);
prevIssue = randomItem.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 updateBuildStatus() {
appendOutput('Debug: updateBuildStatus called', undefined, undefined, true);
const buildTimeStr = buildTimeElement?.getAttribute('data-build-time');
if (!buildTimeStr) {
buildStatus.textContent = '🔨 Build time unknown';
return;
}
const buildTime = new Date(buildTimeStr); // Parse UTC timestamp
const now = new Date();
const nowUTC = new Date(now.toISOString()); // Convert current time to UTC
const diffMs = nowUTC.getTime() - buildTime.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
// Add tooltip with build math
const buildMath = `${buildTimeStr} -> ${diffMs}ms -> ${diffMins}min -> ${diffHours}hr -> ${diffDays}day`;
buildStatus.setAttribute('title', buildMath);
console.log(`Build math: ${buildMath}`);
let agoText = '';
if (diffMins < 1) {
const diffSecs = Math.floor(diffMs / 1000);
if (diffSecs < 10) {
agoText = 'just now';
} else {
agoText = `${diffSecs} sec${diffSecs > 1 ? 's' : ''} ago`;
}
} else if (diffMins < 60) {
agoText = `${diffMins} min${diffMins > 1 ? 's' : ''} ago`;
} else if (diffHours < 24) {
agoText = `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
} else {
agoText = `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
}
buildStatus.textContent = `🔨 Built: ${agoText}`;
buildStatus.style.color = diffMins < 5 ? '#4CAF50' : diffMins < 30 ? '#ff9800' : '#f44336';
}
function handleTestModeToggle() {
testModeEnabled = !testModeEnabled;
testModeBtn.classList.toggle('active', testModeEnabled);
// Update tooltip
const tooltip = testModeEnabled ?
'Test mode ON - Single page fetch (2 pages max) to conserve API rate limits' :
'Test mode OFF - Full pagination (all pages)';
testModeBtn.setAttribute('title', tooltip);
appendOutput(`Test mode ${testModeEnabled ? 'enabled' : 'disabled'} - ${testModeEnabled ? 'single page fetch only' : 'full pagination'}`, undefined, undefined, true);
// Clear cache when toggling test mode to ensure fresh fetch
if (allIssuesGlobal.length > 0) {
allIssuesGlobal = [];
appendOutput('Cache cleared.', undefined, undefined, true);
}
}
function initialize() {
// Test if script is loading
appendOutput('Script loaded successfully!', undefined, undefined, false);
// Add test mode button event listener
if (testModeBtn) {
testModeBtn.addEventListener('click', handleTestModeToggle);
// Initialize tooltip
testModeBtn.setAttribute('title', 'Test mode OFF - Full pagination (all pages)');
}
// Update build status on load
updateBuildStatus();
// Also update build status every 30 seconds
setInterval(updateBuildStatus, 30000);
if (fetchButton && outputDiv && repoInput) {
fetchButton.addEventListener('click', handleFetchClick);
}
if (clearButton && outputDiv) {
clearButton.addEventListener('click', handleClearClick);
}
// Add toggle button event listeners
if (prsCount) {
prsCount.addEventListener('click', () => handleToggleClick('prs'));
}
if (issuesCount) {
issuesCount.addEventListener('click', () => handleToggleClick('issues'));
}
// Initialize toggle button visual states
updateToggleButtonVisual('prs');
updateToggleButtonVisual('issues');
updateDiceButtonState();
// 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();