Github Reply Comments

Easy reply to Github comments

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

  1. // ==UserScript==
  2. // @name Github Reply Comments
  3. // @namespace https://github.com/jerone/UserScripts
  4. // @description Easy reply to Github comments
  5. // @author jerone
  6. // @copyright 2016+, jerone (http://jeroenvanwarmerdam.nl)
  7. // @license GPL-3.0
  8. // @homepage https://github.com/jerone/UserScripts/tree/master/Github_Reply_Comments
  9. // @homepageURL https://github.com/jerone/UserScripts/tree/master/Github_Reply_Comments
  10. // @supportURL https://github.com/jerone/UserScripts/issues
  11. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VCYMHWQ7ZMBKW
  12. // @version 0.1.0
  13. // @icon https://assets-cdn.github.com/pinned-octocat.svg
  14. // @grant none
  15. // @include https://github.com/*
  16. // @include https://gist.github.com/*
  17. // ==/UserScript==
  18.  
  19. (function() {
  20.  
  21. String.format = function(string) {
  22. var args = Array.prototype.slice.call(arguments, 1, arguments.length);
  23. return string.replace(/{(\d+)}/g, function(match, number) {
  24. return typeof args[number] !== "undefined" ? args[number] : match;
  25. });
  26. };
  27.  
  28. /*
  29. * to-markdown - an HTML to Markdown converter
  30. * Copyright 2011, Dom Christie
  31. * Licenced under the MIT licence
  32. * Source: https://github.com/domchristie/to-markdown
  33. *
  34. * Code is altered:
  35. * - Added task list support: https://github.com/domchristie/to-markdown/pull/62
  36. * - He dependecy is removed
  37. */
  38. var toMarkdown = function(string) {
  39.  
  40. var ELEMENTS = [{
  41. patterns: 'p',
  42. replacement: function(str, attrs, innerHTML) {
  43. return innerHTML ? '\n\n' + innerHTML + '\n' : '';
  44. }
  45. }, {
  46. patterns: 'br',
  47. type: 'void',
  48. replacement: ' \n'
  49. }, {
  50. patterns: 'h([1-6])',
  51. replacement: function(str, hLevel, attrs, innerHTML) {
  52. var hPrefix = '';
  53. for (var i = 0; i < hLevel; i++) {
  54. hPrefix += '#';
  55. }
  56. return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
  57. }
  58. }, {
  59. patterns: 'hr',
  60. type: 'void',
  61. replacement: '\n\n* * *\n'
  62. }, {
  63. patterns: 'a',
  64. replacement: function(str, attrs, innerHTML) {
  65. var href = attrs.match(attrRegExp('href')),
  66. title = attrs.match(attrRegExp('title'));
  67. return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
  68. }
  69. }, {
  70. patterns: ['b', 'strong'],
  71. replacement: function(str, attrs, innerHTML) {
  72. return innerHTML ? '**' + innerHTML + '**' : '';
  73. }
  74. }, {
  75. patterns: ['i', 'em'],
  76. replacement: function(str, attrs, innerHTML) {
  77. return innerHTML ? '_' + innerHTML + '_' : '';
  78. }
  79. }, {
  80. patterns: 'code',
  81. replacement: function(str, attrs, innerHTML) {
  82. return innerHTML ? '`' + innerHTML + '`' : '';
  83. }
  84. }, {
  85. patterns: 'img',
  86. type: 'void',
  87. replacement: function(str, attrs) {
  88. var src = attrs.match(attrRegExp('src')),
  89. alt = attrs.match(attrRegExp('alt')),
  90. title = attrs.match(attrRegExp('title'));
  91. return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
  92. }
  93. }];
  94.  
  95. for (var i = 0, len = ELEMENTS.length; i < len; i++) {
  96. if (typeof ELEMENTS[i].patterns === 'string') {
  97. string = replaceEls(string, {
  98. tag: ELEMENTS[i].patterns,
  99. replacement: ELEMENTS[i].replacement,
  100. type: ELEMENTS[i].type
  101. });
  102. } else {
  103. for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
  104. string = replaceEls(string, {
  105. tag: ELEMENTS[i].patterns[j],
  106. replacement: ELEMENTS[i].replacement,
  107. type: ELEMENTS[i].type
  108. });
  109. }
  110. }
  111. }
  112.  
  113. function replaceEls(html, elProperties) {
  114. var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
  115. regex = new RegExp(pattern, 'gi'),
  116. markdown = '';
  117. if (typeof elProperties.replacement === 'string') {
  118. markdown = html.replace(regex, elProperties.replacement);
  119. } else {
  120. markdown = html.replace(regex, function(str, p1, p2, p3) {
  121. return elProperties.replacement.call(this, str, p1, p2, p3);
  122. });
  123. }
  124. return markdown;
  125. }
  126.  
  127. function attrRegExp(attr) {
  128. return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
  129. }
  130.  
  131. // Pre code blocks
  132.  
  133. string = string.replace(/<pre\b[^>]*>`([\s\S]*?)`<\/pre>/gi, function(str, innerHTML) {
  134. var text = innerHTML;
  135. text = text.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense)
  136. text = text.replace(/\n/g, '\n ');
  137. return '\n\n ' + text + '\n';
  138. });
  139.  
  140. // Lists
  141.  
  142. // Escape numbers that could trigger an ol
  143. // If there are more than three spaces before the code, it would be in a pre tag
  144. // Make sure we are escaping the period not matching any character
  145. string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');
  146.  
  147. // Converts lists that have no child lists (of same type) first, then works its way up
  148. var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
  149. while (string.match(noChildrenRegex)) {
  150. string = string.replace(noChildrenRegex, replaceLists);
  151. }
  152.  
  153. function replaceLists(html) {
  154.  
  155. html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) {
  156. var lis = innerHTML.split('</li>');
  157. lis.splice(lis.length - 1, 1);
  158.  
  159. for (i = 0, len = lis.length; i < len; i++) {
  160. if (lis[i]) {
  161. var prefix = (listType === 'ol') ? (i + 1) + ". " : "* ";
  162. lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) {
  163. innerHTML = innerHTML.replace(/\s*<input[^>]*?(checked[^>]*)?type=['"]?checkbox['"]?[^>]>/, function(inputStr, checked) {
  164. return checked ? '[X]' : '[ ]';
  165. });
  166. innerHTML = innerHTML.replace(/^\s+/, '');
  167. innerHTML = innerHTML.replace(/\n\n/g, '\n\n ');
  168. // indent nested lists
  169. innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 ');
  170. return prefix + innerHTML;
  171. });
  172. }
  173. lis[i] = lis[i].replace(/(.) +$/m, '$1');
  174. }
  175. return lis.join('\n');
  176. });
  177.  
  178. return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
  179. }
  180.  
  181. // Blockquotes
  182. var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
  183. while (string.match(deepest)) {
  184. string = string.replace(deepest, replaceBlockquotes);
  185. }
  186.  
  187. function replaceBlockquotes(html) {
  188. html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) {
  189. inner = inner.replace(/^\s+|\s+$/g, '');
  190. inner = cleanUp(inner);
  191. inner = inner.replace(/^/gm, '> ');
  192. inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
  193. return inner;
  194. });
  195. return html;
  196. }
  197.  
  198. function cleanUp(string) {
  199. string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
  200. string = string.replace(/\n\s+\n/g, '\n\n');
  201. string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
  202. return string;
  203. }
  204.  
  205. return cleanUp(string);
  206. };
  207.  
  208. function getCommentTextarea(replyBtn) {
  209. var newComment = replyBtn;
  210. while (newComment && !newComment.classList.contains('js-quote-selection-container')) {
  211. newComment = newComment.parentNode;
  212. }
  213.  
  214. var isReview = !newComment.classList.contains("discussion-timeline");
  215.  
  216. if (newComment) {
  217. var lastElementChild = isReview ? newComment.querySelector(".js-inline-comment-form-container") : newComment.lastElementChild;
  218. lastElementChild.classList.add('open');
  219. newComment = lastElementChild.querySelector(".comment-form-textarea");
  220. } else {
  221. newComment = document.querySelector(".timeline-new-comment .comment-form-textarea");
  222. }
  223. return newComment;
  224. }
  225.  
  226. function addReplyButtons() {
  227. Array.prototype.forEach.call(document.querySelectorAll(".comment, .review-comment"), function(comment) {
  228. var oldReply = comment.querySelector(".GithubReplyComments, .GithubCommentEnhancerReply");
  229. if (oldReply) {
  230. oldReply.parentNode.removeChild(oldReply);
  231. }
  232.  
  233. var header = comment.querySelector(".timeline-comment-header"),
  234. actions = comment.querySelector(".timeline-comment-actions");
  235.  
  236. if (!actions) {
  237. if (!header) {
  238. return;
  239. }
  240. actions = document.createElement("div");
  241. actions.classList.add("timeline-comment-actions");
  242. header.insertBefore(actions, header.firstElementChild);
  243. }
  244.  
  245. var reply = document.createElement("button");
  246. reply.setAttribute("type", "button");
  247. reply.setAttribute("title", "Reply to this comment");
  248. reply.setAttribute("aria-label", "Reply to this comment");
  249. reply.classList.add("GithubReplyComments", "btn-link", "timeline-comment-action", "tooltipped", "tooltipped-ne");
  250. reply.addEventListener("click", function(e) {
  251. e.preventDefault();
  252.  
  253. var newComment = getCommentTextarea(this);
  254.  
  255. var timestamp = comment.querySelector(".timestamp");
  256.  
  257. var commentText = comment.querySelector(".comment-form-textarea");
  258. if (commentText) {
  259. commentText = commentText.value;
  260. } else {
  261. commentText = toMarkdown(comment.querySelector(".comment-body").innerHTML);
  262. }
  263. commentText = commentText.trim().split("\n").map(function(line) {
  264. return "> " + line;
  265. }).join("\n");
  266.  
  267. var text = newComment.value.length > 0 ? "\n" : "";
  268. text += String.format('[**@{0}**]({1}/{0}) commented on [{2}]({3} "{4} - Replied by Github Reply Comments"):\n{5}\n\n',
  269. comment.querySelector(".author").textContent,
  270. location.origin,
  271. timestamp.firstElementChild.getAttribute("title"),
  272. timestamp.href,
  273. timestamp.firstElementChild.getAttribute("datetime"),
  274. commentText);
  275.  
  276. newComment.value += text;
  277. newComment.setSelectionRange(newComment.value.length, newComment.value.length);
  278. newComment.focus();
  279. });
  280.  
  281. var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  282. svg.classList.add("octicon", "octicon-mail-reply");
  283. svg.setAttribute("height", "16");
  284. svg.setAttribute("width", "16");
  285. reply.appendChild(svg);
  286. var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  287. path.setAttribute("d", "M6 2.5l-6 4.5 6 4.5v-3c1.73 0 5.14 0.95 6 4.38 0-4.55-3.06-7.05-6-7.38v-3z");
  288. svg.appendChild(path);
  289.  
  290. actions.appendChild(reply);
  291. });
  292. }
  293.  
  294. // init;
  295. addReplyButtons();
  296.  
  297. // on pjax;
  298. document.addEventListener('pjax:end', addReplyButtons);
  299.  
  300. })();