GitHub 提交訊息顯示網頁視圖

該腳本將 GitHub 上的提交訊息轉換為 HTML 视图,以更清晰地查看提交細節。它會自動將提交訊息列表、提交標題和最新提交訊息轉換為 HTML 格式,提供更佳的視覺效果和使用者體驗。

目前為 2024-09-01 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GitHub CommitMessage Html View
  3. // @name:vi GitHub Tin nhắn cam kết Hiển thị HTML
  4. // @name:en GitHub Commit Message HTML View
  5. // @name:ja GitHub コミットメッセージ HTML ビュー
  6. // @name:ko GitHub 커밋 메시지 HTML 보기
  7. // @name:zh-CN GitHub 提交信息显示网页视图
  8. // @name:zh-TW GitHub 提交訊息顯示網頁視圖
  9. // @name:fr GitHub Affichage des messages de commit en HTML
  10. // @name:de GitHub Commit-Nachricht HTML-Ansicht
  11. // @name:it GitHub Visualizzazione dei messaggi di commit in HTML
  12. // @name:fi GitHub Commit-viestien HTML-näkymä
  13. // @name:sg GitHub Commit Message HTML View
  14. // @name:hk GitHub 提交信息顯示網頁視圖
  15. // @name:mo GitHub 提交信息顯示網頁視圖
  16. // @name:pt GitHub Exibição de Mensagens de Commit em HTML
  17. // @name:ru GitHub Просмотр сообщений коммитов в HTML
  18. // @description This script converts commit messages on GitHub into HTML views for clearer visibility of commit details. It automatically transforms commit message lists, commit headers, and the latest commit information into HTML format, providing enhanced visual appeal and user experience.
  19. // @description:vi Script này chuyển đổi tin nhắn cam kết trên GitHub thành các chế độ xem HTML để rõ ràng hơn về chi tiết cam kết. Nó tự động chuyển đổi danh sách tin nhắn cam kết, tiêu đề cam kết và thông tin cam kết mới nhất thành định dạng HTML, cung cấp sự hấp dẫn về mặt thị giác và trải nghiệm người dùng tốt hơn.
  20. // @description:en This script converts commit messages on GitHub into HTML views for clearer visibility of commit details. It automatically transforms commit message lists, commit headers, and the latest commit information into HTML format, providing enhanced visual appeal and user experience.
  21. // @description:ja このスクリプトは、GitHub 上のコミットメッセージを HTML ビューに変換し、コミットの詳細をより明確に表示します。コミットメッセージのリスト、コミットヘッダー、最新のコミット情報を自動的に HTML 形式に変換し、視覚的な魅力とユーザー体験を向上させます。
  22. // @description:ko 이 스크립트는 GitHub의 커밋 메시지를 HTML 뷰로 변환하여 커밋 세부 정보를 보다 명확하게 볼 수 있도록 합니다. 커밋 메시지 목록, 커밋 헤더 및 최신 커밋 정보를 자동으로 HTML 형식으로 변환하여 시각적 매력과 사용자 경험을 향상시킵니다.
  23. // @description:zh-CN 该脚本将 GitHub 上的提交信息转化为 HTML 视图,以更清晰地查看提交详情。它会自动将提交信息列表、提交头部和最新提交信息转化为 HTML 格式,提供更佳的视觉效果和用户体验。
  24. // @description:zh-TW 該腳本將 GitHub 上的提交訊息轉換為 HTML 视图,以更清晰地查看提交細節。它會自動將提交訊息列表、提交標題和最新提交訊息轉換為 HTML 格式,提供更佳的視覺效果和使用者體驗。
  25. // @description:fr Ce script convertit les messages de commit sur GitHub en vues HTML pour une meilleure visibilité des détails des commits. Il transforme automatiquement les listes de messages de commit, les en-têtes de commit et les informations sur le dernier commit en format HTML, offrant ainsi un attrait visuel et une expérience utilisateur améliorés.
  26. // @description:de Dieses Skript konvertiert Commit-Nachrichten auf GitHub in HTML-Ansichten, um die Details der Commits klarer sichtbar zu machen. Es wandelt automatisch Commit-Nachrichtendaten, Commit-Kopfzeilen und die neuesten Commit-Informationen in HTML-Format um und bietet eine verbesserte visuelle Darstellung und Benutzererfahrung.
  27. // @description:it Questo script converte i messaggi di commit su GitHub in visualizzazioni HTML per una visibilità più chiara dei dettagli dei commit. Trasforma automaticamente le liste dei messaggi di commit, le intestazioni dei commit e le informazioni sull'ultimo commit in formato HTML, offrendo un'appeal visivo e un'esperienza utente migliorati.
  28. // @description:fi Tämä skripti muuntaa GitHubin commit-viestit HTML-näkymiksi, jotta commit-tiedot ovat selkeämmin näkyvissä. Se muuntaa automaattisesti commit-viestilistat, commit-otsikot ja viimeisimmät commit-tiedot HTML-muotoon, tarjoten parannettua visuaalista vetovoimaa ja käyttäjäkokemusta.
  29. // @description:sg This script converts commit messages on GitHub into HTML views for clearer visibility of commit details. It automatically transforms commit message lists, commit headers, and the latest commit information into HTML format, providing enhanced visual appeal and user experience.
  30. // @description:hk 該腳本將 GitHub 上的提交信息轉換為 HTML 视图,以更清晰地查看提交詳情。它會自動將提交信息列表、提交標題和最新提交信息轉換為 HTML 格式,提供更佳的視覺效果和使用者體驗。
  31. // @description:mo 該腳本將 GitHub 上的提交信息轉換為 HTML 视图,以更清晰地查看提交詳情。它會自動將提交信息列表、提交標題和最新提交信息轉換為 HTML 格式,提供更佳的視覺效果和使用者體驗。
  32. // @description:pt Este script converte mensagens de commit no GitHub em visualizações HTML para uma visibilidade mais clara dos detalhes dos commits. Ele transforma automaticamente listas de mensagens de commit, cabeçalhos de commit e informações sobre o último commit em formato HTML, proporcionando maior atratividade visual e experiência do usuário.
  33. // @description:ru Этот скрипт преобразует сообщения коммитов на GitHub в HTML-виды для более четкого отображения деталей коммитов. Он автоматически преобразует списки сообщений коммитов, заголовки коммитов и информацию о последнем коммите в формат HTML, обеспечивая улучшенную визуальную привлекательность и пользовательский опыт.
  34. // @version 1.0.0.6
  35. // @namespace https://github.com/ChinaGodMan
  36. // @author 人民的勤务员 <toniaiwanowskiskr47@gmail.com>
  37. // @match *://github.com/*/*
  38. // @grant GM_registerMenuCommand
  39. // @grant none
  40. // @icon https://github.githubassets.com/pinned-octocat.svg
  41. // @license MIT
  42. // @source https://github.com/qinwuyuan-cn/UserScripts
  43. // @supportURL https://github.com/ChinaGodMan/UserScripts/issues
  44. // @homepageURL https://github.com/ChinaGodMan/UserScripts
  45. // ==/UserScript==
  46. const selectors = {
  47. commitList: {
  48. value: '.react-directory-commit-message a', // 选择提交消息列表中的链接
  49. description: '选择仓库列表中的提交信息'
  50. },
  51. commitListFound: false,
  52. commitHeader: {
  53. value: '.fgColor-muted > span[data-testid="latest-commit-html"]', // 选择最新提交的头部信息
  54. description: '选择仓库列表头部展开详细信息'
  55. },
  56. commitHeaderScreen: {
  57. value: 'span.Truncate-text[data-testid="latest-commit-html"]', // 头部小预览
  58. description: '选择头部预览小标题'
  59. },
  60. commitLastTime: {
  61. value: 'div.react-directory-commit-age', // 选择最新提交的头部信息
  62. description: '获取最新提交信息'
  63. },
  64. commitHeaderIsRun: false,
  65. commitHeaderFound: false,
  66. commitHeaderScreenIsRun: false,
  67. commitHeaderScreenFound: false,
  68. }
  69. let LastCommitText = ""
  70. let LastCommitHref = ""
  71. let wocaonima = null
  72. function updateCommitMessageInDetails(selector) {//详情页,
  73. const element = document.querySelector(selector)
  74. if (!element) return
  75. const textContent = element.textContent.trim()
  76. if (!containsHTML(textContent)) return
  77. if (wocaonima) {
  78. element.innerHTML = wocaonima
  79. } else {
  80. element.innerHTML = textContent
  81. }
  82. }
  83. function updateRepoHeaderExpandCommit(selector) {//头部展开
  84. const spanElements = document.querySelectorAll(selector)
  85. spanElements.forEach(spanElement => {
  86. const parentElement = spanElement.parentElement
  87. const textContent = spanElement.textContent.trim()
  88. const linkElement = spanElement.querySelector('a')
  89. const hrefValue = linkElement.getAttribute('href')
  90. if (containsHTML(textContent)) {
  91. if (!LastCommitHref || !LastCommitText) {
  92. spanElement.innerHTML = `<a href="${hrefValue}">` + textContent + `</a>`
  93. } else {
  94. spanElement.innerHTML = `<a href="${LastCommitHref}">` + LastCommitText + `</a>`
  95. }
  96. }
  97. })
  98. }
  99. //
  100. function updateRepoHeaderScreenCommit(selector) {
  101. const spanElements = document.querySelectorAll(selector)
  102. spanElements.forEach(spanElement => {
  103. const parentElement = spanElement.parentElement
  104. const textContent = spanElement.textContent.trim()
  105. const linkElement = spanElement.querySelector('a')
  106. const hrefValue = linkElement.getAttribute('href')
  107. if (containsHTML(textContent)) {
  108. spanElement.addEventListener('click', () => {
  109. wocaonima = spanElement.innerHTML
  110. })
  111. if (!LastCommitHref || !LastCommitText) {
  112. console.log("未通过点击跳转:", textContent)
  113. spanElement.innerHTML = `<a href="${hrefValue}">` + textContent + `</a>`
  114. } else {
  115. console.log("通过点击跳转", LastCommitText)
  116. spanElement.innerHTML = `<a href="${LastCommitHref}">` + LastCommitText + `</a>`
  117. }
  118. }
  119. })
  120. }
  121. function updateRepoListCommit(selector) {
  122. const commitMessages = document.querySelectorAll(selector)
  123. commitMessages.forEach(element => {
  124. const nextElement = element.nextElementSibling
  125. if (nextElement) (
  126. nextElement.remove()
  127. )
  128. const titleContent = element.getAttribute("title")
  129. const hrefValue = element.getAttribute("href")
  130. if (titleContent) {
  131. if (containsHTML(titleContent)) {
  132. element.addEventListener('click', () => {
  133. wocaonima = element.innerHTML
  134. })
  135. element.innerHTML = `<a href="${hrefValue}">${titleContent}</a>`
  136. }
  137. }
  138. })
  139. }
  140. function getLastTimeCommit(selector) {
  141. const allElements = document.querySelectorAll(selector)
  142. let latestElement = null
  143. let latestDate = new Date(0)
  144. allElements.forEach(div => {
  145. const relativeTime = div.querySelector('relative-time')
  146. if (relativeTime) {
  147. const datetime = relativeTime.getAttribute('datetime')
  148. if (datetime) {
  149. const currentDate = new Date(datetime)
  150. if (currentDate > latestDate) {
  151. latestDate = currentDate
  152. latestElement = div
  153. }
  154. }
  155. }
  156. })
  157. if (latestElement) {
  158. const parentTd = latestElement.closest('td')
  159. if (parentTd) {
  160. const previousTd = parentTd.previousElementSibling
  161. const linkElement = previousTd.querySelector(selectors.commitList.value)
  162. LastCommitText = linkElement.getAttribute("title")
  163. LastCommitHref = linkElement.getAttribute("href")
  164. return { previousTd, linkElement }
  165. } else {
  166. return null
  167. }
  168. } else {
  169. return null
  170. }
  171. }
  172. function containsHTML(str) {
  173. const pattern = /<\/?[a-z][\s\S]*>/i
  174. return pattern.test(str)
  175. }
  176. /**
  177. * 监视 DOM 变化,直到找到符合选择器的元素,然后执行指定的回调函数。
  178. * @param {string} selector - 要匹配的选择器。
  179. * @param {function} callback - 找到匹配元素后的回调函数。
  180. */
  181. function observeForElement(selector, callback, disconnect = true, DEBUG = "操作", isElementFound) {
  182. isElementFound = false
  183. const observer = new MutationObserver((mutationsList, observer) => {
  184. mutationsList.forEach(mutation => {
  185. if (mutation.type === 'childList') {
  186. const element = document.querySelector(selector)
  187. if (element) {
  188. if (!isElementFound) {
  189. console.log(`成功执行:${DEBUG} - ${selector} `)
  190. isElementFound = true
  191. callback(element)
  192. if (disconnect) {
  193. observer.disconnect()
  194. } //else { console.log(`没有断开监听器器: ${DEBUG} - ${selector} `) }
  195. }
  196. }
  197. }
  198. })
  199. })
  200. observer.observe(document.body, {
  201. childList: true,
  202. subtree: true
  203. })
  204. if (!disconnect) {
  205. const removalObserver = new MutationObserver(mutationsList => {
  206. mutationsList.forEach(mutation => {
  207. mutation.removedNodes.forEach(node => {
  208. const element = document.querySelector(selector)
  209. if (!element) {
  210. // console.log(`继续查找: ${DEBUG} ${selector}`)
  211. isElementFound = false
  212. }
  213. })
  214. })
  215. })
  216. removalObserver.observe(document.body, {
  217. childList: true,
  218. subtree: true
  219. })
  220. }
  221. }
  222. function observeForElement_______________________________(selector, callback) {
  223. let isElementFound = false
  224. const observer = new MutationObserver((mutationsList, observer) => {
  225. mutationsList.forEach(mutation => {
  226. if (mutation.type === 'childList' && !isElementFound) {
  227. const element = document.querySelector(selector)
  228. if (element) {
  229. console.log("成功找到仓库列表中的提交信息元素")
  230. isElementFound = true
  231. callback(element)//留着以后用
  232. observer.disconnect()
  233. }
  234. }
  235. })
  236. })
  237. observer.observe(document.body, {
  238. childList: true,
  239. subtree: true
  240. })
  241. }
  242. main()
  243. watchUpdate()
  244. function main() {
  245. LastCommitText = ""
  246. LastCommitHref = ""
  247. observeForElement(selectors.commitList.value, function (element) {
  248. updateRepoListCommit(selectors.commitList.value)
  249. },
  250. true,
  251. selectors.commitList.description,
  252. selectors.commitListFound)
  253. if (!selectors.commitHeaderIsRun) {
  254. selectors.commitHeaderIsRun = true
  255. observeForElement(
  256. selectors.commitHeader.value,
  257. function (element) {
  258. getLastTimeCommit(selectors.commitLastTime.value)//从列表获取最新的提交信息,作为进入或返回目录使用
  259. updateRepoHeaderExpandCommit(selectors.commitHeader.value)
  260. },
  261. false,
  262. selectors.commitHeader.description,
  263. selectors.commitHeaderFound
  264. )
  265. }
  266. selectors.commitHeaderScreenIsRun = false
  267. if (!selectors.commitHeaderScreenIsRun) {
  268. observeForElement(
  269. selectors.commitHeaderScreen.value,
  270. function (element) {
  271. getLastTimeCommit(selectors.commitLastTime.value)//从列表获取最新的提交信息,作为进入或返回目录使用
  272. updateRepoHeaderScreenCommit(selectors.commitHeaderScreen.value)//头部预览
  273. },
  274. false,
  275. selectors.commitHeaderScreen.description,
  276. selectors.commitHeaderScreenIsRun
  277. )
  278. }
  279. //updateCommitMessageInDetails('.commit-desc')
  280. const element = document.querySelector('.commit-title.markdown-title')
  281. if (element) {
  282. element.remove()
  283. }
  284. updateCommitMessageInDetails('.commit-desc')
  285. //updateCommitMessageInDetails('.commit-title.markdown-title')
  286. wocaonima = null
  287. //
  288. }
  289. function watchUpdate() {//检查链接变化
  290. // 检测浏览器是否支持 MutationObserver
  291. const MutationObserver =
  292. window.MutationObserver ||
  293. window.WebKitMutationObserver ||
  294. window.MozMutationObserver
  295. // 获取当前页面的 URL
  296. const getCurrentURL = () => location.href
  297. getCurrentURL.previousURL = getCurrentURL()
  298. // 创建 MutationObserver 实例,监听 DOM 变化
  299. const observer = new MutationObserver((mutations, observer) => {
  300. const currentURL = getCurrentURL()
  301. // 如果页面的 URL 发生变化
  302. if (currentURL !== getCurrentURL.previousURL) {
  303. getCurrentURL.previousURL = currentURL
  304. console.log(`链接变化,正在启动监听器`)
  305. setTimeout(() => {
  306. main()
  307. }, 500)
  308. }
  309. })
  310. // 配置 MutationObserver
  311. const config = {
  312. characterData: true,
  313. subtree: true,
  314. childList: true,
  315. attributeFilter: ['value', 'placeholder', 'aria-label', 'data-confirm'], // 仅观察特定属性变化
  316. }
  317. // 开始观察 document.body 的变化
  318. observer.observe(document.body, config)
  319. }