Repository navigation
Expand file tree
/
Copy pathextension.js
More file actions
381 lines (340 loc) · 14.4 KB
/
Copy pathextension.js
File metadata and controls
381 lines (340 loc) · 14.4 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
// SPDX-FileCopyrightText: 2026 Daniel Arndt <dan@arndt.ca>
// SPDX-License-Identifier: GPL-2.0-or-later
import GLib from 'gi://GLib';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import { Extension } from 'resource:///org/gnome/shell/extensions/extension.js';
import { Indicator } from './src/ui/indicator.js';
import { GithubClient, RequestCancelledError } from './src/api/githubClient.js';
import { loadToken } from './src/api/keyring.js';
import { syncClientToken, TOKEN_CHANGED_KEY } from './src/api/tokenSync.js';
import { RepoFilter } from './src/models/repoFilter.js';
import { PRItem } from './src/models/prItem.js';
import { collectPRNodes } from './src/models/prNodes.js';
import {
getPRKey,
recordSnooze,
removeSnooze,
recordDismissal,
removeDismissal,
pruneMissingKeys,
categorizeAndPruneDismissed,
} from './src/models/dismissTracker.js';
import {
snapshotCategories,
detectTransitions,
describeTransitions,
} from './src/models/transitionTracker.js';
export default class GitHubPRExtension extends Extension {
enable() {
this._settings = this.getSettings();
this._rawNodes = [];
this._rawPRItems = [];
this._lastCategories = null;
this._viewerLogin = this._settings.get_string('last-username') || '';
this._repoFilter = new RepoFilter({
includeStr: this._settings.get_string('include-repos'),
excludeStr: this._settings.get_string('exclude-repos'),
ignoreArchived: this._settings.get_boolean('ignore-archived'),
ignoreForks: this._settings.get_boolean('ignore-forks'),
});
this._githubClient = new GithubClient();
this._indicator = new Indicator(
this,
() => this.refreshData(),
{
onSnooze: (pr) => this.snoozePR(pr),
onDismiss: (pr) => this.dismissPR(pr),
onRestore: (pr) => this.restorePR(pr),
onUndo: (pr) => this.restorePR(pr),
}
);
Main.panel.addToStatusArea(this.uuid, this._indicator);
if (this._viewerLogin) {
this._indicator.menuView.setUsername(this._viewerLogin);
}
this._settingsChangedIds = [
this._settings.connect('changed::refresh-interval', () => this._startTimer()),
this._settings.connect('changed::include-repos', () => this._onFilterSettingsChanged()),
this._settings.connect('changed::exclude-repos', () => this._onFilterSettingsChanged()),
this._settings.connect('changed::ignore-archived', () => this._onFilterSettingsChanged()),
this._settings.connect('changed::ignore-forks', () => this._onFilterSettingsChanged()),
this._settings.connect('changed::include-team-reviews', () => this._onFilterSettingsChanged()),
this._settings.connect('changed::include-assigned-prs', () => this._onFilterSettingsChanged()),
this._settings.connect(`changed::${TOKEN_CHANGED_KEY}`, () => this.refreshData()),
];
// Start polling synchronously so nothing needs to run after an await
// if the extension is disabled while the first refresh is pending.
this._startTimer();
this.refreshData();
}
disable() {
if (this._timerId) {
GLib.Source.remove(this._timerId);
this._timerId = null;
}
// Drop results of any refresh still in flight; destroying the client
// below rejects its pending request.
this._bumpRefreshGeneration();
if (this._settingsChangedIds && this._settings) {
for (const id of this._settingsChangedIds) {
this._settings.disconnect(id);
}
this._settingsChangedIds = [];
}
if (this._githubClient) {
this._githubClient.destroy();
this._githubClient = null;
}
if (this._indicator) {
this._indicator.destroy();
this._indicator = null;
}
this._settings = null;
this._repoFilter = null;
this._rawNodes = [];
this._rawPRItems = [];
this._lastCategories = null;
}
/**
* Drops cached PR data and clears the panel badges and menu sections.
*/
_clearData() {
this._rawNodes = [];
this._rawPRItems = [];
this._lastCategories = null;
this._indicator.updateCounts(new Map());
this._indicator.menuView.setLastUpdated(null);
}
_onFilterSettingsChanged() {
this._repoFilter.updateSettings({
includeStr: this._settings.get_string('include-repos'),
excludeStr: this._settings.get_string('exclude-repos'),
ignoreArchived: this._settings.get_boolean('ignore-archived'),
ignoreForks: this._settings.get_boolean('ignore-forks'),
});
// Re-classify and re-filter cached PR items without making another network request
if (this._rawNodes.length > 0) {
const includeTeamReviews = this._settings.get_boolean('include-team-reviews');
const includeAssignedPRs = this._settings.get_boolean('include-assigned-prs');
this._rawPRItems = this._rawNodes.map(
node => new PRItem(node, this._viewerLogin, { includeTeamReviews, includeAssignedPRs })
);
this._applyFilterAndDisplay(this._rawPRItems);
}
}
_startTimer() {
if (this._timerId) {
GLib.Source.remove(this._timerId);
this._timerId = null;
}
const intervalMinutes = Math.max(1, this._settings.get_int('refresh-interval') || 5);
this._timerId = GLib.timeout_add_seconds(
GLib.PRIORITY_DEFAULT,
intervalMinutes * 60,
() => {
this.refreshData();
return GLib.SOURCE_CONTINUE;
}
);
}
/**
* Invalidates any refresh currently in flight so its results are dropped.
* @returns {number} the new refresh generation
*/
_bumpRefreshGeneration() {
this._refreshGeneration = (this._refreshGeneration ?? 0) + 1;
return this._refreshGeneration;
}
/**
* Fetches fresh PR data from GitHub GraphQL API.
*
* Overlapping calls are allowed (timer, manual refresh, token change);
* only the most recent one updates the UI.
*/
async refreshData() {
const generation = this._bumpRefreshGeneration();
const isCurrent = () => generation === this._refreshGeneration;
// Always re-read the keyring so tokens saved, replaced or cleared in
// Preferences take effect without re-enabling the extension.
let hasToken;
try {
hasToken = await syncClientToken(this._githubClient, loadToken);
} catch (err) {
if (!isCurrent()) return;
console.error('[GitHub PR Tracker] Keyring load error:', err);
this._indicator.menuView.showError('Failed to access system keyring.');
return;
}
if (!isCurrent()) return;
if (!hasToken) {
this._clearData();
this._indicator.menuView.showTokenRequired();
return;
}
this._indicator.menuView.setLoading(true);
try {
const { data, errors } = await this._githubClient.fetchAllPRs();
if (!isCurrent()) return;
const viewerLogin = data.viewer?.login || '';
if (viewerLogin && viewerLogin !== this._viewerLogin) {
this._viewerLogin = viewerLogin;
this._settings.set_string('last-username', viewerLogin);
}
this._indicator.menuView.setUsername(this._viewerLogin);
const { nodes, truncated } = collectPRNodes(data);
this._rawNodes = nodes;
const includeTeamReviews = this._settings.get_boolean('include-team-reviews');
const includeAssignedPRs = this._settings.get_boolean('include-assigned-prs');
this._rawPRItems = this._rawNodes.map(
node => new PRItem(node, this._viewerLogin, { includeTeamReviews, includeAssignedPRs })
);
// Forget snoozes/dismissals of PRs that are gone (merged, closed, review
// no longer requested), but only when nothing could be missing
// from this response
if (errors.length === 0 && !truncated) {
const { snoozed, dismissed } = this._loadMaps();
const fetchedKeys = new Set(this._rawPRItems.map(getPRKey));
const snoozedPruned = pruneMissingKeys(snoozed, fetchedKeys);
const dismissedPruned = pruneMissingKeys(dismissed, fetchedKeys);
if (snoozedPruned || dismissedPruned) {
this._saveMaps(snoozed, dismissed);
}
}
this._applyFilterAndDisplay(this._rawPRItems);
this._indicator.menuView.setLastUpdated(new Date(), truncated);
// Partial results: show what loaded, but flag what did not
if (errors.length > 0) {
for (const e of errors) {
console.warn('[GitHub PR Tracker] Partial GraphQL error:', e.message);
}
this._indicator.menuView.showError(
`Some pull requests could not be loaded: ${errors[0].message}`
);
}
} catch (err) {
// A superseded or cancelled request leaves the UI to the newer one.
if (!isCurrent() || err instanceof RequestCancelledError) return;
console.error('[GitHub PR Tracker] Error fetching data:', err);
this._indicator.menuView.showError(err.message || 'Error fetching data.');
} finally {
if (isCurrent()) {
this._indicator.menuView.setLoading(false);
}
}
}
_loadMaps() {
let snoozed = {};
let dismissed = {};
if (this._settings) {
try {
const sStr = this._settings.get_string('snoozed-prs');
snoozed = sStr ? JSON.parse(sStr) : {};
} catch (err) {
console.error('[GitHub PR Tracker] Error parsing snoozed-prs:', err);
snoozed = {};
}
try {
const dStr = this._settings.get_string('dismissed-prs');
dismissed = dStr ? JSON.parse(dStr) : {};
} catch (err) {
console.error('[GitHub PR Tracker] Error parsing dismissed-prs:', err);
dismissed = {};
}
// Migration: if snoozed-prs is empty but dismissed-prs contains ISO timestamp strings
// (the old format from previous versions which behaved as snooze), migrate them to snoozed-prs.
if (Object.keys(snoozed).length === 0 && Object.keys(dismissed).length > 0) {
let migrated = false;
for (const [key, val] of Object.entries(dismissed)) {
if (typeof val === 'string') {
snoozed[key] = val;
delete dismissed[key];
migrated = true;
}
}
if (migrated) {
this._settings.set_string('snoozed-prs', JSON.stringify(snoozed));
this._settings.set_string('dismissed-prs', JSON.stringify(dismissed));
}
}
}
return { snoozed, dismissed };
}
_saveMaps(snoozed, dismissed) {
if (this._settings) {
if (snoozed !== undefined) {
this._settings.set_string('snoozed-prs', JSON.stringify(snoozed || {}));
}
if (dismissed !== undefined) {
this._settings.set_string('dismissed-prs', JSON.stringify(dismissed || {}));
}
}
}
/**
* Snoozes a pull request until it receives a new update on GitHub.
* @param {PRItem} prItem
*/
snoozePR(prItem) {
if (!prItem) return;
const { snoozed, dismissed } = this._loadMaps();
recordSnooze(prItem, snoozed);
removeDismissal(prItem, dismissed);
this._saveMaps(snoozed, dismissed);
this._applyFilterAndDisplay(this._rawPRItems);
}
/**
* Permanently dismisses a pull request.
* @param {PRItem} prItem
*/
dismissPR(prItem) {
if (!prItem) return;
const { snoozed, dismissed } = this._loadMaps();
recordDismissal(prItem, dismissed);
removeSnooze(prItem, snoozed);
this._saveMaps(snoozed, dismissed);
this._applyFilterAndDisplay(this._rawPRItems);
}
/**
* Restores a snoozed or dismissed pull request back to its active category.
* @param {PRItem} prItem
*/
restorePR(prItem) {
if (!prItem) return;
const { snoozed, dismissed } = this._loadMaps();
removeSnooze(prItem, snoozed);
removeDismissal(prItem, dismissed);
this._saveMaps(snoozed, dismissed);
this._applyFilterAndDisplay(this._rawPRItems);
}
/**
* Applies repository filters, handles snoozed/dismissed PRs, and distributes PRs to categories.
* @param {Array<PRItem>} prItems
*/
_applyFilterAndDisplay(prItems) {
const filtered = prItems.filter(item => item && item.category && this._repoFilter.matches(item));
const { snoozed, dismissed } = this._loadMaps();
const { categorizedMap, snoozedChanged, dismissedChanged } = categorizeAndPruneDismissed(
filtered,
snoozed,
dismissed
);
if (snoozedChanged || dismissedChanged) {
this._saveMaps(snoozed, dismissed);
}
this._notifyTransitions(categorizedMap);
this._indicator.updateCounts(categorizedMap);
}
/**
* Sends a desktop notification for PRs that changed category since the
* previous display. The first display only records a baseline.
* @param {Map<string, Array<PRItem>>} categorizedMap
*/
_notifyTransitions(categorizedMap) {
const previous = this._lastCategories;
this._lastCategories = snapshotCategories(categorizedMap);
if (!previous || !this._settings.get_boolean('notify-on-transition')) return;
const transitions = detectTransitions(previous, categorizedMap);
if (transitions.length === 0) return;
const { title, body } = describeTransitions(transitions);
Main.notify(title, body);
}
}