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
|
import './mark-unread.css';
import React from 'dom-chef';
import select from 'select-dom';
import elementReady from 'element-ready';
import delegate, {DelegateSubscription, DelegateEvent} from 'delegate-it';
import features from '../libs/features';
import * as icons from '../libs/icons';
import * as pageDetect from '../libs/page-detect';
import {getUsername, getRepoURL} from '../libs/utils';
import onUpdatableContentUpdate from '../libs/on-updatable-content-update';
type NotificationType = 'pull-request' | 'issue';
type NotificationState = 'open' | 'merged' | 'closed' | 'draft';
interface Participant {
username: string;
avatar: string;
}
interface Notification {
participants: Participant[];
state: NotificationState;
isParticipating: boolean;
repository: string;
dateTitle: string;
title: string;
type: NotificationType;
date: string;
url: string;
}
const listeners: DelegateSubscription[] = [];
const stateIcons = {
issue: {
open: icons.openIssue,
closed: icons.closedIssue,
merged: icons.closedIssue, // Required just for TypeScript
draft: icons.closedIssue // Required just for TypeScript
},
'pull-request': {
open: icons.openPullRequest,
closed: icons.closedPullRequest,
merged: icons.mergedPullRequest,
draft: icons.openPullRequest
}
};
async function getNotifications(): Promise<Notification[]> {
const {unreadNotifications} = await browser.storage.local.get({
unreadNotifications: []
});
// Only show notifications for the current domain. Accounts for gist.github.com as well
return unreadNotifications.filter(({url}: Notification) => location.hostname.endsWith(new URL(url).hostname));
}
async function setNotifications(unreadNotifications: Notification[]): Promise<void> {
return browser.storage.local.set({unreadNotifications});
}
function stripHash(url: string): string {
return url.replace(/#.+$/, '');
}
function addMarkUnreadButton(): void {
if (!select.exists('.rgh-btn-mark-unread')) {
select('.thread-subscription-status')!.after(
<button className="btn btn-sm btn-block mt-2 rgh-btn-mark-unread" onClick={markUnread}>
Mark as unread
</button>
);
}
}
async function markRead(urls: string|string[]): Promise<void> {
if (!Array.isArray(urls)) {
urls = [urls];
}
const cleanUrls = urls.map(stripHash);
for (const a of select.all<HTMLAnchorElement>('a.js-notification-target')) {
if (cleanUrls.includes(a.getAttribute('href')!)) {
a.closest('li.js-notification')!.classList.replace('unread', 'read');
}
}
const notifications = await getNotifications();
const updated = notifications.filter(({url}) => !cleanUrls.includes(url));
await setNotifications(updated);
}
async function markUnread({currentTarget}: React.MouseEvent): Promise<void> {
const participants: Participant[] = select.all('.participant-avatar').slice(0, 3).map(el => ({
username: el.getAttribute('aria-label')!,
avatar: el.querySelector('img')!.src
}));
const stateLabel = select('.gh-header-meta .State')!;
let state: NotificationState;
if (stateLabel.classList.contains('State--green')) {
state = 'open';
} else if (stateLabel.classList.contains('State--purple')) {
state = 'merged';
} else if (stateLabel.classList.contains('State--red')) {
state = 'closed';
} else if (stateLabel.title.includes('Draft')) {
state = 'draft';
} else {
throw new Error('Refined GitHub: A new issue state was introduced?');
}
const lastCommentTime = select.last<HTMLTimeElement>('.timeline-comment-header relative-time')!;
const unreadNotifications = await getNotifications();
unreadNotifications.push({
participants,
state,
isParticipating: select.exists(`.participant-avatar[href="/${getUsername()}"]`),
repository: getRepoURL(),
dateTitle: lastCommentTime.title,
title: select('.js-issue-title')!.textContent!.trim(),
type: pageDetect.isPR() ? 'pull-request' : 'issue',
date: lastCommentTime.getAttribute('datetime')!,
url: stripHash(location.href)
});
await setNotifications(unreadNotifications);
await updateUnreadIndicator();
currentTarget.setAttribute('disabled', 'disabled');
currentTarget.textContent = 'Marked as unread';
}
function getNotification(notification: Notification): Element {
const {
participants,
dateTitle,
title,
state,
type,
date,
url
} = notification;
const existing = select(`a.js-notification-target[href^="${stripHash(url)}"]`);
if (existing) {
const item = existing.closest('.js-notification')!;
item.classList.replace('read', 'unread');
return item;
}
const usernames = participants
.map(participant => participant.username)
.join(' and ')
.replace(/ and (.+) and/, ', $1, and'); // 3 people only: A, B, and C
const avatars = participants.map(participant =>
<a href={`/${participant.username}`} className="avatar">
<img alt={`@${participant.username}`} height="20" src={participant.avatar} width="20"/>
</a>
);
return (
<li className={`list-group-item js-notification js-navigation-item unread ${type}-notification rgh-unread`}>
<span className="list-group-item-name css-truncate">
<span className={`type-icon type-icon-state-${state}`}>
{stateIcons[type][state]()}
</span>
<a className="css-truncate-target js-notification-target js-navigation-open list-group-item-link" href={url}
data-hovercard-url={`${url}/hovercard?show_subscription_status=true`}>
{title}
</a>
</span>
<ul className="notification-actions">
<li className="delete">
<button className="btn-link delete-note">
{icons.check()}
</button>
</li>
<li className="mute tooltipped tooltipped-w" aria-label={`${type === 'issue' ? 'Issue' : 'PR'} manually marked as unread`}>
{icons.info()}
</li>
<li className="age">
<relative-time datetime={date} title={dateTitle}/>
</li>
<div className="AvatarStack AvatarStack--three-plus AvatarStack--right clearfix d-inline-block" style={{marginTop: 1}}>
<div className="AvatarStack-body tooltipped tooltipped-sw tooltipped-align-right-1" aria-label={usernames}>
{avatars}
</div>
</div>
</ul>
</li>
);
}
function getNotificationGroup({repository}: Notification): Element {
const existing = select(`a.notifications-repo-link[title="${repository}"]`)!;
if (existing) {
return existing.closest('.boxed-group')!;
}
return (
<div className="boxed-group flush">
<form className="boxed-group-action">
<button className="mark-all-as-read css-truncate js-mark-all-read">
{icons.check()}
</button>
</form>
<h3>
<a href={'/' + repository} className="css-truncate css-truncate-target notifications-repo-link" title={repository}>
{repository}
</a>
</h3>
<ul className="boxed-group-inner list-group notifications"/>
</div>
);
}
async function renderNotifications(unreadNotifications: Notification[]): Promise<void> {
unreadNotifications = unreadNotifications.filter(shouldNotificationAppearHere);
if (unreadNotifications.length === 0) {
return;
}
// Don’t simplify selector, it’s for cross-extension compatibility
let pageList = (await elementReady('#notification-center .notifications-list'))!;
if (!pageList) {
pageList = <div className="notifications-list"></div>;
select('.blankslate')!.replaceWith(pageList);
}
unreadNotifications.reverse().forEach(notification => {
const group = getNotificationGroup(notification);
const item = getNotification(notification);
pageList.prepend(group);
group
.querySelector('ul.notifications')!
.prepend(item);
});
// Make sure that all the boxes with unread items are at the top
// This is necessary in the "All notifications" view
for (const repo of select.all('.boxed-group').reverse()) {
if (select.exists('.unread', repo)) {
pageList.prepend(repo);
}
}
}
function shouldNotificationAppearHere(notification: Notification): boolean {
if (isSingleRepoPage()) {
return isCurrentSingleRepoPage(notification);
}
if (isParticipatingPage()) {
return notification.isParticipating;
}
return true;
}
function isSingleRepoPage(): boolean {
return location.pathname.split('/')[3] === 'notifications';
}
function isCurrentSingleRepoPage({repository}: Notification): boolean {
const [, singleRepo = ''] = /^[/](.+[/].+)[/]notifications/.exec(location.pathname) || [];
return singleRepo === repository;
}
function isParticipatingPage(): boolean {
return location.pathname.startsWith('/notifications/participating');
}
async function updateUnreadIndicator(): Promise<void> {
const icon = select<HTMLAnchorElement>('a.notification-indicator')!; // "a" required in responsive views
if (!icon) {
return;
}
const statusMark = icon.querySelector('.mail-status')!;
if (!statusMark) {
return;
}
const hasRealNotifications = icon.matches('[data-ga-click$=":unread"]');
const rghUnreadCount = (await getNotifications()).length;
const hasUnread = hasRealNotifications || rghUnreadCount > 0;
const label = hasUnread ? 'You have unread notifications' : 'You have no unread notifications';
icon.setAttribute('aria-label', label);
statusMark.classList.toggle('unread', hasUnread);
if (rghUnreadCount > 0) {
icon.dataset.rghUnread = String(rghUnreadCount); // Store in attribute to let other extensions know
} else {
delete icon.dataset.rghUnread;
}
}
async function markNotificationRead({delegateTarget}: DelegateEvent): Promise<void> {
const {href} = delegateTarget
.closest('li.js-notification')!
.querySelector<HTMLAnchorElement>('a.js-notification-target')!;
await markRead(href);
await updateUnreadIndicator();
}
async function markAllNotificationsRead(event: DelegateEvent): Promise<void> {
event.preventDefault();
const repoGroup = event.delegateTarget.closest('.boxed-group')!;
const urls = select.all<HTMLAnchorElement>('a.js-notification-target', repoGroup).map(a => a.href);
await markRead(urls);
await updateUnreadIndicator();
}
async function markVisibleNotificationsRead({delegateTarget}: DelegateEvent): Promise<void> {
const group = delegateTarget.closest('.boxed-group')!;
const repo = select('.notifications-repo-link', group)!.textContent;
const notifications = await getNotifications();
setNotifications(notifications.filter(({repository}) => repository !== repo));
}
function addCustomAllReadBtn(): void {
const nativeMarkUnreadForm = select('details [action="/notifications/mark"]');
if (nativeMarkUnreadForm) {
nativeMarkUnreadForm.addEventListener('submit', () => {
setNotifications([]);
});
return;
}
select('.tabnav .float-right')!.append(
<details className="details-reset details-overlay details-overlay-dark lh-default text-gray-dark d-inline-block text-left">
<summary className="btn btn-sm" aria-haspopup="dialog">
Mark all as read
</summary>
<details-dialog className="Box Box--overlay d-flex flex-column anim-fade-in fast " aria-label="Are you sure?" role="dialog" tabindex="-1">
<div className="Box-header">
<button className="Box-btn-octicon btn-octicon float-right" type="button" aria-label="Close dialog" data-close-dialog="">
{icons.x()}
</button>
<h3 className="Box-title">Are you sure?</h3>
</div>
<div className="Box-body">
<p>Are you sure you want to mark all unread notifications as read?</p>
<button type="button" className="btn btn-block" id="clear-local-notification">Mark all notifications as read</button>
</div>
</details-dialog>
</details>
);
delegate('#clear-local-notification', 'click', async () => {
await setNotifications([]);
location.reload();
});
}
function updateLocalNotificationsCount(localNotifications: Notification[]): void {
const unreadCount = select('#notification-center .filter-list a[href="/notifications"] .count')!;
const githubNotificationsCount = Number(unreadCount.textContent);
unreadCount.textContent = String(githubNotificationsCount + localNotifications.length);
}
function updateLocalParticipatingCount(notifications: Notification[]): void {
const participatingNotifications = notifications
.filter(({isParticipating}) => isParticipating)
.length;
if (participatingNotifications > 0) {
const unreadCount = select('#notification-center .filter-list a[href="/notifications/participating"] .count')!;
const githubNotificationsCount = Number(unreadCount.textContent);
unreadCount.textContent = String(githubNotificationsCount + participatingNotifications);
}
}
function destroy(): void {
for (const listener of listeners) {
listener.destroy();
}
listeners.length = 0;
}
async function init(): Promise<void> {
destroy();
if (pageDetect.isNotifications()) {
const notifications = await getNotifications();
if (notifications.length > 0) {
await renderNotifications(notifications);
addCustomAllReadBtn();
updateLocalNotificationsCount(notifications);
updateLocalParticipatingCount(notifications);
document.dispatchEvent(new CustomEvent('refined-github:mark-unread:notifications-added'));
}
listeners.push(
delegate('.btn-link.delete-note', 'click', markNotificationRead),
delegate('.js-mark-all-read', 'click', markAllNotificationsRead),
delegate('.js-delete-notification button', 'click', updateUnreadIndicator),
delegate('.js-mark-visible-as-read', 'submit', markVisibleNotificationsRead)
);
} else if (pageDetect.isPR() || pageDetect.isIssue()) {
await markRead(location.href);
addMarkUnreadButton();
onUpdatableContentUpdate(select('#partial-discussion-sidebar')!, addMarkUnreadButton);
} else if (pageDetect.isDiscussionList()) {
for (const discussion of await getNotifications()) {
const {pathname} = new URL(discussion.url);
const listItem = select(`.read [href='${pathname}']`);
if (listItem) {
listItem.closest('.read')!.classList.replace('read', 'unread');
}
}
}
updateUnreadIndicator();
}
features.add({
id: __featureName__,
description: 'Adds button to mark issues and PRs as unread. They will reappear in Notifications.',
screenshot: 'https://user-images.githubusercontent.com/1402241/27847663-963b7d7c-6171-11e7-9470-6e86d8463771.png',
load: features.onAjaxedPagesRaw,
init
});
|