Refined GitHub Notifications

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

当前为 2023-04-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Refined GitHub Notifications
  3. // @namespace https://greasyfork.org/en/scripts/461320-refined-github-notifications
  4. // @version 0.2.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 none
  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. const TIMEOUT = 60_000
  25. const NAME = 'Refined GitHub Notifications'
  26. let lastUpdate = Date.now()
  27.  
  28. let bc
  29. let bcInitTime = 0
  30.  
  31. function injectStyle() {
  32. const style = document.createElement('style')
  33. style.innerHTML = `
  34. /* Hide blue dot on notification icon */
  35. .mail-status.unread {
  36. display: none !important;
  37. }
  38. .js-notification-shelf {
  39. display: none !important;
  40. }
  41. `
  42. document.head.appendChild(style)
  43. }
  44.  
  45. /**
  46. * To have a FAB button to close current issue,
  47. * where you can mark done and then close the tab automatically
  48. */
  49. function notificationShelf() {
  50. function inject() {
  51. const shelf = document.querySelector('.js-notification-shelf')
  52. if (!shelf)
  53. return false
  54.  
  55. const containers = document.createElement('div')
  56. Object.assign(containers.style, {
  57. position: 'fixed',
  58. right: '20px',
  59. bottom: '20px',
  60. zIndex: 999,
  61. display: 'flex',
  62. flexDirection: 'column',
  63. gap: '10px',
  64. })
  65. document.body.appendChild(containers)
  66.  
  67. const doneButton = shelf.querySelector('button[title="Done"]')
  68. // const unsubscribeButton = shelf.querySelector('button[title="Unsubscribe"]')
  69.  
  70. const buttons = [
  71. // unsubscribeButton,
  72. doneButton,
  73. ].filter(Boolean)
  74.  
  75. for (const button of buttons) {
  76. const clickAndClose = async () => {
  77. button.click()
  78. await new Promise(resolve => setTimeout(resolve, 100))
  79. window.close()
  80. }
  81.  
  82. const fab = button.cloneNode(true)
  83. fab.classList.remove('btn-sm')
  84. fab.style.aspectRatio = '1/1'
  85. fab.style.broderRadius = '100%'
  86. fab.addEventListener('click', clickAndClose)
  87. containers.appendChild(fab)
  88.  
  89. if (button === doneButton) {
  90. document.addEventListener('keydown', (e) => {
  91. if ((e.metaKey || e.ctrlKey) && e.key === 'x') {
  92. e.preventDefault()
  93. clickAndClose()
  94. }
  95. })
  96. }
  97. }
  98.  
  99. return true
  100. }
  101.  
  102. // when first into the page, the notification shelf might not be loaded, we need to wait for it to show
  103. if (!inject()) {
  104. const observer = new MutationObserver((mutationList) => {
  105. const found = mutationList.some(i => i.type === 'childList' && Array.from(i.addedNodes).some(el => el.classList.contains('js-notification-shelf')))
  106. if (found) {
  107. inject()
  108. observer.disconnect()
  109. }
  110. })
  111. observer.observe(document.querySelector('[data-turbo-body]'), { childList: true })
  112. }
  113. }
  114.  
  115. function initBroadcastChannel() {
  116. bcInitTime = Date.now()
  117. bc = new BroadcastChannel('refined-github-notifications')
  118.  
  119. bc.onmessage = ({ data }) => {
  120. console.log(`[${NAME}]`, 'Received message', data)
  121. if (data.type === 'check-dedupe') {
  122. // If the new tab is opened after the current tab, close the current tab
  123. if (data.time > bcInitTime)
  124. location.href = 'https://close-me.netlify.app'
  125. }
  126. }
  127. }
  128.  
  129. function dedupeTab() {
  130. if (!bc)
  131. return
  132. bc.postMessage({ type: 'check-dedupe', time: bcInitTime, url: location.href })
  133. }
  134.  
  135. function externalize() {
  136. document.querySelectorAll('a')
  137. .forEach((r) => {
  138. if (r.href.startsWith('https://github.com/notifications'))
  139. return
  140. r.target = '_blank'
  141. r.rel = 'noopener noreferrer'
  142. })
  143. }
  144.  
  145. function initIdleListener() {
  146. // Auto refresh page on going back to the page
  147. document.addEventListener('visibilitychange', (e) => {
  148. if (document.visibilityState === 'visible')
  149. refresh()
  150. })
  151. }
  152.  
  153. function getIssues() {
  154. return [...document.querySelectorAll('.notifications-list-item')]
  155. .map((el) => {
  156. const url = el.querySelector('a.notification-list-item-link').href
  157. const status = el.querySelector('.color-fg-open')
  158. ? 'open'
  159. : el.querySelector('.color-fg-done')
  160. ? 'done'
  161. : el.querySelector('.color-fg-closed')
  162. ? 'closed'
  163. : el.querySelector('.color-fg-muted')
  164. ? 'muted'
  165. : 'unknown'
  166.  
  167. const notificationTypeEl = el.querySelector('.AvatarStack').nextElementSibling
  168. const notificationType = notificationTypeEl.textContent.trim()
  169.  
  170. // Colorize notification type
  171. if (notificationType === 'mention')
  172. notificationTypeEl.classList.add('color-fg-open')
  173. else if (notificationType === 'subscribed')
  174. notificationTypeEl.classList.add('color-fg-muted')
  175. else if (notificationType === 'review requested')
  176. notificationTypeEl.classList.add('color-fg-done')
  177.  
  178. const item = {
  179. title: el.querySelector('.markdown-title').textContent.trim(),
  180. el,
  181. url,
  182. read: el.classList.contains('notification-read'),
  183. starred: el.classList.contains('notification-starred'),
  184. type: notificationType,
  185. status,
  186. isClosed: ['closed', 'done', 'muted'].includes(status),
  187. markDone: () => {
  188. console.log(`[${NAME}]`, 'Mark notifications done', item)
  189. el.querySelector('button[type=submit] .octicon-check').parentElement.parentElement.click()
  190. },
  191. }
  192.  
  193. return item
  194. })
  195. }
  196.  
  197. function getReasonMarkedDone(item) {
  198. if (item.isClosed && (item.read || item.type === 'subscribed'))
  199. return 'Closed / merged'
  200.  
  201. if (item.title.startsWith('chore(deps): update ') && (item.read || item.type === 'subscribed'))
  202. return 'Renovate bot'
  203.  
  204. if (item.url.match('/pull/[0-9]+/files/'))
  205. return 'New commit pushed to PR'
  206.  
  207. if (item.type === 'ci activity' && /workflow run cancell?ed/.test(item.title))
  208. return 'GH PR Audit Action workflow run cancelled, probably due to another run taking precedence'
  209. }
  210.  
  211. function isInboxView() {
  212. const query = new URLSearchParams(window.location.search).get('query')
  213. if (!query)
  214. return true
  215.  
  216. const conditions = query.split(' ')
  217. return ['is:done', 'is:saved'].every(condition => !conditions.includes(condition))
  218. }
  219.  
  220. function autoMarkDone() {
  221. // Only mark on "Inbox" view
  222. if (!isInboxView())
  223. return
  224.  
  225. const items = getIssues()
  226.  
  227. console.log(`[${NAME}] ${items}`)
  228. let count = 0
  229.  
  230. const done = []
  231.  
  232. items.forEach((i) => {
  233. // skip bookmarked notifications
  234. if (i.starred)
  235. return
  236.  
  237. const reason = getReasonMarkedDone(i)
  238. if (!reason)
  239. return
  240.  
  241. count++
  242. i.markDone()
  243. done.push({
  244. title: i.title,
  245. reason,
  246. link: i.link,
  247. })
  248. })
  249.  
  250. if (done.length) {
  251. console.log(`[${NAME}]`, `${count} notifications marked done`)
  252. console.table(done)
  253. }
  254.  
  255. // Refresh page after marking done (expand the pagination)
  256. if (count >= 5)
  257. setTimeout(() => refresh(), 200)
  258. }
  259.  
  260. function removeBotAvatars() {
  261. document.querySelectorAll('.AvatarStack-body > a')
  262. .forEach((r) => {
  263. if (r.href.startsWith('/apps/') || r.href.startsWith('https://github.com/apps/'))
  264. r.remove()
  265. })
  266. }
  267.  
  268. /**
  269. * The "x new notifications" badge
  270. */
  271. function hasNewNotifications() {
  272. return !!document.querySelector('.js-updatable-content a[href="/notifications?query="]')
  273. }
  274.  
  275. // Click the notification tab to do soft refresh
  276. function refresh() {
  277. if (!isInNotificationPage())
  278. return
  279. document.querySelector('.filter-list a[href="/notifications"]').click()
  280. lastUpdate = Date.now()
  281. }
  282.  
  283. function isInNotificationPage() {
  284. return location.href.startsWith('https://github.com/notifications')
  285. }
  286.  
  287. function observeForNewNotifications() {
  288. try {
  289. const observer = new MutationObserver(() => {
  290. if (hasNewNotifications())
  291. refresh()
  292. })
  293. observer.observe(document.querySelector('.js-check-all-container').children[0], {
  294. childList: true,
  295. subtree: true,
  296. })
  297. }
  298. catch (e) {
  299. }
  300. }
  301.  
  302. ////////////////////////////////////////
  303.  
  304. let initialized = false
  305.  
  306. function run() {
  307. if (isInNotificationPage()) {
  308. // Run only once
  309. if (!initialized) {
  310. initIdleListener()
  311. initBroadcastChannel()
  312. observeForNewNotifications()
  313. initialized = true
  314. }
  315.  
  316. // Run every render
  317. dedupeTab()
  318. externalize()
  319. removeBotAvatars()
  320. autoMarkDone()
  321. }
  322. else {
  323. notificationShelf()
  324. }
  325. }
  326.  
  327. injectStyle()
  328. run()
  329.  
  330. // listen to github page loaded event
  331. document.addEventListener('pjax:end', () => run())
  332. document.addEventListener('turbo:render', () => run())
  333. })()