Refined GitHub Notifications

Enhances the GitHub Notifications page, making it more productive and less noisy.

当前为 2023-05-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Refined GitHub Notifications
  3. // @namespace https://greasyfork.org/en/scripts/461320-refined-github-notifications
  4. // @version 0.4.1
  5. // @description Enhances the GitHub Notifications page, making it more productive and less noisy.
  6. // @author Anthony Fu (https://github.com/antfu)
  7. // @license MIT
  8. // @homepageURL https://github.com/antfu/refined-github-notifications
  9. // @supportURL https://github.com/antfu/refined-github-notifications
  10. // @match https://github.com/**
  11. // @icon https://www.google.com/s2/favicons?sz=64&domain=github.com
  12. // @grant window.close
  13. // ==/UserScript==
  14.  
  15. /* eslint-disable no-console */
  16.  
  17. (function () {
  18. 'use strict'
  19.  
  20. // Fix the archive link
  21. if (location.pathname === '/notifications/beta/archive')
  22. location.pathname = '/notifications'
  23.  
  24. // list of functions to be cleared on page change
  25. const cleanups = []
  26.  
  27. const NAME = 'Refined GitHub Notifications'
  28. const STORAGE_KEY = 'refined-github-notifications'
  29.  
  30. const config = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}')
  31.  
  32. let bc
  33. let bcInitTime = 0
  34.  
  35. function writeConfig() {
  36. localStorage.setItem(STORAGE_KEY, JSON.stringify(config))
  37. }
  38.  
  39. function injectStyle() {
  40. const style = document.createElement('style')
  41. style.innerHTML = `
  42. /* Hide blue dot on notification icon */
  43. .mail-status.unread {
  44. display: none !important;
  45. }
  46. /* Hide blue dot on notification with the new navigration */
  47. .AppHeader .AppHeader-button.AppHeader-button--hasIndicator::before {
  48. display: none !important;
  49. }
  50. /* Hide the notification shelf and add a FAB */
  51. .js-notification-shelf {
  52. display: none !important;
  53. }
  54. .btn-hover-primary {
  55. transform: scale(1.2);
  56. transition: all .3s ease-in-out;
  57. }
  58. .btn-hover-primary:hover {
  59. color: var(--color-btn-primary-text);
  60. background-color: var(--color-btn-primary-bg);
  61. border-color: var(--color-btn-primary-border);
  62. box-shadow: var(--color-btn-primary-shadow),var(--color-btn-primary-inset-shadow);
  63. }
  64. /* Hide the image on zero-inbox */
  65. .js-notifications-blankslate picture {
  66. display: none !important;
  67. }
  68. /* Limit notification container width on large screen for better readability */
  69. .notifications-v2 .js-check-all-container {
  70. max-width: 1000px;
  71. margin: 0 auto;
  72. }
  73. `
  74. document.head.appendChild(style)
  75. }
  76.  
  77. /**
  78. * To have a FAB button to close current issue,
  79. * where you can mark done and then close the tab automatically
  80. */
  81. function notificationShelf() {
  82. function inject() {
  83. const shelf = document.querySelector('.js-notification-shelf')
  84. if (!shelf)
  85. return false
  86.  
  87. const doneButton = shelf.querySelector('button[title="Done"]')
  88. if (!doneButton)
  89. return false
  90.  
  91. const clickAndClose = async () => {
  92. doneButton.click()
  93. // wait for the notification shelf to be updated
  94. await Promise.race([
  95. new Promise((resolve) => {
  96. const ob = new MutationObserver(() => {
  97. resolve()
  98. ob.disconnect()
  99. })
  100. .observe(
  101. shelf,
  102. {
  103. childList: true,
  104. subtree: true,
  105. attributes: true,
  106. },
  107. )
  108. }),
  109. new Promise(resolve => setTimeout(resolve, 1000)),
  110. ])
  111. // close the tab
  112. window.close()
  113. }
  114. const keyDownHandle = (e) => {
  115. if (e.metaKey && e.key === 'x') {
  116. e.preventDefault()
  117. clickAndClose()
  118. }
  119. }
  120.  
  121. const fab = doneButton.cloneNode(true)
  122. fab.classList.remove('btn-sm')
  123. fab.classList.add('btn-hover-primary')
  124. fab.addEventListener('click', clickAndClose)
  125. Object.assign(fab.style, {
  126. position: 'fixed',
  127. right: '25px',
  128. bottom: '25px',
  129. zIndex: 999,
  130. aspectRatio: '1/1',
  131. borderRadius: '50%',
  132. })
  133.  
  134. const commentActions = document.querySelector('#partial-new-comment-form-actions')
  135. if (commentActions) {
  136. const key = 'markDoneAfterComment'
  137. const label = document.createElement('label')
  138. const input = document.createElement('input')
  139. label.classList.add('color-fg-muted')
  140. input.type = 'checkbox'
  141. input.checked = !!config[key]
  142. input.addEventListener('change', (e) => {
  143. config[key] = !!e.target.checked
  144. writeConfig()
  145. })
  146. label.appendChild(input)
  147. label.appendChild(document.createTextNode(' Mark done and close after comment'))
  148. Object.assign(label.style, {
  149. display: 'flex',
  150. alignItems: 'center',
  151. justifyContent: 'end',
  152. gap: '5px',
  153. userSelect: 'none',
  154. fontWeight: '400',
  155. })
  156. const div = document.createElement('div')
  157. Object.assign(div.style, {
  158. paddingBottom: '5px',
  159. })
  160. div.appendChild(label)
  161. commentActions.parentElement.prepend(div)
  162.  
  163. const commentButton = commentActions.querySelector('button.btn-primary[type="submit"]')
  164. const closeButton = commentActions.querySelector('[name="comment_and_close"]')
  165. const buttons = [commentButton, closeButton].filter(Boolean)
  166.  
  167. for (const button of buttons) {
  168. button.addEventListener('click', async () => {
  169. if (config[key]) {
  170. await new Promise(resolve => setTimeout(resolve, 1000))
  171. clickAndClose()
  172. }
  173. })
  174. }
  175. }
  176.  
  177. const mergeMessage = document.querySelector('.merge-message')
  178. if (mergeMessage) {
  179. const key = 'markDoneAfterMerge'
  180. const label = document.createElement('label')
  181. const input = document.createElement('input')
  182. label.classList.add('color-fg-muted')
  183. input.type = 'checkbox'
  184. input.checked = !!config[key]
  185. input.addEventListener('change', (e) => {
  186. config[key] = !!e.target.checked
  187. writeConfig()
  188. })
  189. label.appendChild(input)
  190. label.appendChild(document.createTextNode(' Mark done and close after merge'))
  191. Object.assign(label.style, {
  192. display: 'flex',
  193. alignItems: 'center',
  194. justifyContent: 'end',
  195. gap: '5px',
  196. userSelect: 'none',
  197. fontWeight: '400',
  198. })
  199. mergeMessage.prepend(label)
  200.  
  201. const buttons = mergeMessage.querySelectorAll('.js-auto-merge-box button')
  202. for (const button of buttons) {
  203. button.addEventListener('click', async () => {
  204. if (config[key]) {
  205. await new Promise(resolve => setTimeout(resolve, 1000))
  206. clickAndClose()
  207. }
  208. })
  209. }
  210. }
  211.  
  212. document.body.appendChild(fab)
  213. document.addEventListener('keydown', keyDownHandle)
  214. cleanups.push(() => {
  215. document.body.removeChild(fab)
  216. document.removeEventListener('keydown', keyDownHandle)
  217. })
  218.  
  219. return true
  220. }
  221.  
  222. // when first into the page, the notification shelf might not be loaded, we need to wait for it to show
  223. if (!inject()) {
  224. const observer = new MutationObserver((mutationList) => {
  225. const found = mutationList.some(i => i.type === 'childList' && Array.from(i.addedNodes).some(el => el.classList.contains('js-notification-shelf')))
  226. if (found) {
  227. inject()
  228. observer.disconnect()
  229. }
  230. })
  231. observer.observe(document.querySelector('[data-turbo-body]'), { childList: true })
  232. cleanups.push(() => {
  233. observer.disconnect()
  234. })
  235. }
  236. }
  237.  
  238. function initBroadcastChannel() {
  239. bcInitTime = Date.now()
  240. bc = new BroadcastChannel('refined-github-notifications')
  241.  
  242. bc.onmessage = ({ data }) => {
  243. if (isInNotificationPage()) {
  244. console.log(`[${NAME}]`, 'Received message', data)
  245. if (data.type === 'check-dedupe') {
  246. // If the new tab is opened after the current tab, close the current tab
  247. if (data.time > bcInitTime) {
  248. window.close()
  249. location.href = 'https://close-me.netlify.app'
  250. }
  251. }
  252. }
  253. }
  254. }
  255.  
  256. function dedupeTab() {
  257. if (!bc)
  258. return
  259. bc.postMessage({ type: 'check-dedupe', time: bcInitTime, url: location.href })
  260. }
  261.  
  262. function externalize() {
  263. document.querySelectorAll('a')
  264. .forEach((r) => {
  265. if (r.href.startsWith('https://github.com/notifications'))
  266. return
  267. // try to use the same tab
  268. r.target = r.href.replace('https://github.com', '').replace(/[\\/?#-]/g, '_')
  269. })
  270. }
  271.  
  272. function initIdleListener() {
  273. // Auto refresh page on going back to the page
  274. document.addEventListener('visibilitychange', () => {
  275. if (document.visibilityState === 'visible')
  276. refresh()
  277. })
  278. }
  279.  
  280. function getIssues() {
  281. return [...document.querySelectorAll('.notifications-list-item')]
  282. .map((el) => {
  283. const url = el.querySelector('a.notification-list-item-link').href
  284. const status = el.querySelector('.color-fg-open')
  285. ? 'open'
  286. : el.querySelector('.color-fg-done')
  287. ? 'done'
  288. : el.querySelector('.color-fg-closed')
  289. ? 'closed'
  290. : el.querySelector('.color-fg-muted')
  291. ? 'muted'
  292. : 'unknown'
  293.  
  294. const notificationTypeEl = el.querySelector('.AvatarStack').nextElementSibling
  295. const notificationType = notificationTypeEl.textContent.trim()
  296.  
  297. // Colorize notification type
  298. if (notificationType === 'mention' || notificationType === 'author')
  299. notificationTypeEl.classList.add('color-fg-open')
  300. else if (notificationType === 'subscribed')
  301. notificationTypeEl.remove()
  302. else if (notificationType === 'state change')
  303. notificationTypeEl.classList.add('color-fg-muted')
  304. else if (notificationType === 'review requested')
  305. notificationTypeEl.classList.add('color-fg-done')
  306.  
  307. const plusOneEl = [...el.querySelectorAll('.d-md-flex')]
  308. .find(i => i.textContent.trim().startsWith('+'))
  309. if (plusOneEl)
  310. plusOneEl.remove()
  311.  
  312. const item = {
  313. title: el.querySelector('.markdown-title').textContent.trim(),
  314. el,
  315. url,
  316. read: el.classList.contains('notification-read'),
  317. starred: el.classList.contains('notification-starred'),
  318. type: notificationType,
  319. status,
  320. isClosed: ['closed', 'done', 'muted'].includes(status),
  321. markDone: () => {
  322. console.log(`[${NAME}]`, 'Mark notifications done', item)
  323. el.querySelector('button[type=submit] .octicon-check').parentElement.parentElement.click()
  324. },
  325. }
  326.  
  327. return item
  328. })
  329. }
  330.  
  331. function getReasonMarkedDone(item) {
  332. if (item.isClosed && (item.read || item.type === 'subscribed'))
  333. return 'Closed / merged'
  334.  
  335. if (item.title.startsWith('chore(deps): update ') && (item.read || item.type === 'subscribed'))
  336. return 'Renovate bot'
  337.  
  338. if (item.url.match('/pull/[0-9]+/files/'))
  339. return 'New commit pushed to PR'
  340.  
  341. if (item.type === 'ci activity' && /workflow run cancell?ed/.test(item.title))
  342. return 'GH PR Audit Action workflow run cancelled, probably due to another run taking precedence'
  343. }
  344.  
  345. function isInboxView() {
  346. const query = new URLSearchParams(window.location.search).get('query')
  347. if (!query)
  348. return true
  349.  
  350. const conditions = query.split(' ')
  351. return ['is:done', 'is:saved'].every(condition => !conditions.includes(condition))
  352. }
  353.  
  354. function autoMarkDone() {
  355. // Only mark on "Inbox" view
  356. if (!isInboxView())
  357. return
  358.  
  359. const items = getIssues()
  360.  
  361. console.log(`[${NAME}] ${items}`)
  362. let count = 0
  363.  
  364. const done = []
  365.  
  366. items.forEach((i) => {
  367. // skip bookmarked notifications
  368. if (i.starred)
  369. return
  370.  
  371. const reason = getReasonMarkedDone(i)
  372. if (!reason)
  373. return
  374.  
  375. count++
  376. i.markDone()
  377. done.push({
  378. title: i.title,
  379. reason,
  380. link: i.link,
  381. })
  382. })
  383.  
  384. if (done.length) {
  385. console.log(`[${NAME}]`, `${count} notifications marked done`)
  386. console.table(done)
  387. }
  388.  
  389. // Refresh page after marking done (expand the pagination)
  390. if (count >= 5)
  391. setTimeout(() => refresh(), 200)
  392. }
  393.  
  394. function removeBotAvatars() {
  395. document.querySelectorAll('.AvatarStack-body > a')
  396. .forEach((r) => {
  397. if (r.href.startsWith('/apps/') || r.href.startsWith('https://github.com/apps/'))
  398. r.remove()
  399. })
  400. }
  401.  
  402. /**
  403. * The "x new notifications" badge
  404. */
  405. function hasNewNotifications() {
  406. return !!document.querySelector('.js-updatable-content a[href="/notifications?query="]')
  407. }
  408.  
  409. function cleanup() {
  410. cleanups.forEach(fn => fn())
  411. cleanups.length = 0
  412. }
  413.  
  414. // Click the notification tab to do soft refresh
  415. function refresh() {
  416. if (!isInNotificationPage())
  417. return
  418. document.querySelector('.filter-list a[href="/notifications"]').click()
  419. }
  420.  
  421. function isInNotificationPage() {
  422. return location.href.startsWith('https://github.com/notifications')
  423. }
  424.  
  425. function observeForNewNotifications() {
  426. try {
  427. const observer = new MutationObserver(() => {
  428. if (hasNewNotifications())
  429. refresh()
  430. })
  431. observer.observe(document.querySelector('.js-check-all-container').children[0], {
  432. childList: true,
  433. subtree: true,
  434. })
  435. }
  436. catch (e) {
  437. }
  438. }
  439.  
  440. ////////////////////////////////////////
  441.  
  442. let initialized = false
  443.  
  444. function run() {
  445. cleanup()
  446. if (isInNotificationPage()) {
  447. // Run only once
  448. if (!initialized) {
  449. initIdleListener()
  450. initBroadcastChannel()
  451. observeForNewNotifications()
  452. initialized = true
  453. }
  454.  
  455. // Run every render
  456. dedupeTab()
  457. externalize()
  458. removeBotAvatars()
  459. autoMarkDone()
  460. }
  461. else {
  462. notificationShelf()
  463. }
  464. }
  465.  
  466. injectStyle()
  467. run()
  468.  
  469. // listen to github page loaded event
  470. document.addEventListener('pjax:end', () => run())
  471. document.addEventListener('turbo:render', () => run())
  472. })()