Add Sourcegraph Button to GitHub

Add a 'Sourcrgraph' Button on GitHub repository & file page.

2020-06-18 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name Add Sourcegraph Button to GitHub
  3. // @description Add a 'Sourcrgraph' Button on GitHub repository & file page.
  4. // @version 5
  5. // @grant none
  6. // @inject-into auto
  7. // @supportURL https://github.com/whtsky/userscripts/issues
  8. // @match https://github.com/*
  9. // @namespace https://greatest.deepsurf.us/users/164794
  10. // ==/UserScript==
  11.  
  12. const pats = [
  13. ['^/([^/]+)/([^/]+)/tree/([^/]+)$', '/github.com/$1/$2@$3'],
  14. ['^/([^/]+)/([^/]+)/tree/([^/]+)/(.+)$', '/github.com/$1/$2@$3/-/tree/$4'],
  15. ['^/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$', '/github.com/$1/$2@$3/-/blob/$4'],
  16. ['^/([^/]+)/([^/]+)/?$', '/github.com/$1/$2'],
  17. ['^/([^/]+)/?$', '/$1'],
  18. ].map(([reg, replaceValue]) => ({
  19. regexp: new RegExp(reg),
  20. replaceValue,
  21. }))
  22.  
  23. const buttonID = 'userscript__sourcegraph'
  24.  
  25. function getSourceGraphUrl() {
  26. var pathname = window.location.pathname
  27. for (const { regexp, replaceValue } of pats) {
  28. if (pathname.match(regexp)) {
  29. const pathname2 = pathname.replace(regexp, replaceValue)
  30. return 'https://sourcegraph.com' + pathname2
  31. }
  32. }
  33. }
  34.  
  35. /**
  36. * @returns {HTMLAnchorElement | null}
  37. */
  38. function getCreatedButton() {
  39. return document.querySelector(`#${buttonID}`)
  40. }
  41.  
  42. function createButton() {
  43. if (getCreatedButton()) {
  44. return
  45. }
  46.  
  47. const targetBtn =
  48. document.querySelector('#raw-url') ||
  49. document.querySelector('.file-navigation a.BtnGroup-item') ||
  50. document.querySelector('.file-navigation a.d-md-block')
  51. if (targetBtn) {
  52. /**
  53. * @type {HTMLAnchorElement}
  54. */
  55. const newBtn = targetBtn.cloneNode(false)
  56. newBtn.setAttribute('id', buttonID)
  57. newBtn.textContent = 'Sourcegraph'
  58. newBtn.href = getSourceGraphUrl()
  59. targetBtn.parentNode.insertBefore(newBtn, targetBtn)
  60. }
  61. }
  62.  
  63. window.addEventListener('popstate', function() {
  64. const button = getCreatedButton()
  65. if (button) {
  66. button.href = getSourceGraphUrl()
  67. }
  68. })
  69.  
  70. const observer = new MutationObserver(function() {
  71. observer.disconnect()
  72. createButton()
  73. observer.observe(document.body, { childList: true, subtree: true })
  74. })
  75. observer.observe(document.body, { childList: true, subtree: true })
  76.  
  77. createButton()