Refined GitHub Notifications

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

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

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