Github Comment Enhancer

Enhances Github comments

当前为 2015-03-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @id Github_Comment_Enhancer@https://github.com/jerone/UserScripts
  3. // @name Github Comment Enhancer
  4. // @namespace https://github.com/jerone/UserScripts
  5. // @description Enhances Github comments
  6. // @author jerone
  7. // @copyright 2014+, jerone (http://jeroenvanwarmerdam.nl)
  8. // @license GNU GPLv3
  9. // @homepage https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer
  10. // @homepageURL https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer
  11. // @supportURL https://github.com/jerone/UserScripts/issues
  12. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VCYMHWQ7ZMBKW
  13. // @version 2.2.0
  14. // @grant none
  15. // @run-at document-end
  16. // @include https://github.com/*/*/issues
  17. // @include https://github.com/*/*/issues/*
  18. // @include https://github.com/*/*/pulls
  19. // @include https://github.com/*/*/pull/*
  20. // @include https://github.com/*/*/commit/*
  21. // @include https://github.com/*/*/compare/*
  22. // @include https://github.com/*/*/wiki/*
  23. // @include https://gist.github.com/*
  24. // ==/UserScript==
  25. /* global unsafeWindow */
  26.  
  27. (function(unsafeWindow) {
  28.  
  29. String.format = function(string) {
  30. var args = Array.prototype.slice.call(arguments, 1, arguments.length);
  31. return string.replace(/{(\d+)}/g, function(match, number) {
  32. return typeof args[number] !== "undefined" ? args[number] : match;
  33. });
  34. };
  35.  
  36. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/langs/markdown.js
  37. var MarkDown = (function MarkDown() {
  38. return {
  39. "function-bold": {
  40. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  41. replace: "$1**$2**$3"
  42. },
  43. "function-italic": {
  44. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  45. replace: "$1_$2_$3"
  46. },
  47. "function-strikethrough": {
  48. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  49. replace: "$1~~$2~~$3"
  50. },
  51.  
  52. "function-h1": {
  53. search: /(.+)([\n]?)/g,
  54. replace: "# $1$2",
  55. forceNewline: true
  56. },
  57. "function-h2": {
  58. search: /(.+)([\n]?)/g,
  59. replace: "## $1$2",
  60. forceNewline: true
  61. },
  62. "function-h3": {
  63. search: /(.+)([\n]?)/g,
  64. replace: "### $1$2",
  65. forceNewline: true
  66. },
  67. "function-h4": {
  68. search: /(.+)([\n]?)/g,
  69. replace: "#### $1$2",
  70. forceNewline: true
  71. },
  72. "function-h5": {
  73. search: /(.+)([\n]?)/g,
  74. replace: "##### $1$2",
  75. forceNewline: true
  76. },
  77. "function-h6": {
  78. search: /(.+)([\n]?)/g,
  79. replace: "###### $1$2",
  80. forceNewline: true
  81. },
  82.  
  83. "function-link": {
  84. exec: function(button, selText, commentForm, next) {
  85. var selTxt = selText.trim(),
  86. isUrl = selTxt && /(?:https?:\/\/)|(?:www\.)/.test(selTxt),
  87. href = window.prompt("Link href:", isUrl ? selTxt : ""),
  88. text = window.prompt("Link text:", isUrl ? "" : selTxt);
  89. if (href) {
  90. next(String.format("[{0}]({1}){2}", text || href, href, (/\s+$/.test(selText) ? " " : "")));
  91. }
  92. }
  93. },
  94. "function-image": {
  95. exec: function(button, selText, commentForm, next) {
  96. var selTxt = selText.trim(),
  97. isUrl = selTxt && /(?:https?:\/\/)|(?:www\.)/.test(selTxt),
  98. href = window.prompt("Image href:", isUrl ? selTxt : ""),
  99. text = window.prompt("Image text:", isUrl ? "" : selTxt);
  100. if (href) {
  101. next(String.format("![{0}]({1}){2}", text || href, href, (/\s+$/.test(selText) ? " " : "")));
  102. }
  103. }
  104. },
  105.  
  106. "function-ul": {
  107. search: /(.+)([\n]?)/g,
  108. replace: "* $1$2",
  109. forceNewline: true
  110. },
  111. "function-ol": {
  112. exec: function(button, selText, commentForm, next) {
  113. var repText = "";
  114. if (!selText) {
  115. repText = "1. ";
  116. } else {
  117. var lines = selText.split("\n"),
  118. hasContent = /[\w]+/;
  119. for (var i = 0; i < lines.length; i++) {
  120. if (hasContent.test(lines[i])) {
  121. repText += String.format("{0}. {1}\n", i + 1, lines[i]);
  122. }
  123. }
  124. }
  125. next(repText);
  126. }
  127. },
  128. "function-checklist": {
  129. search: /(.+)([\n]?)/g,
  130. replace: "* [ ] $1$2",
  131. forceNewline: true
  132. },
  133.  
  134. "function-code": {
  135. exec: function(button, selText, commentForm, next) {
  136. var rt = selText.indexOf("\n") > -1 ? "$1\n```\n$2\n```$3" : "$1`$2`$3";
  137. next(selText.replace(/^(\s*)([\s\S]*?)(\s*)$/g, rt));
  138. }
  139. },
  140. "function-blockquote": {
  141. search: /(.+)([\n]?)/g,
  142. replace: "> $1$2",
  143. forceNewline: true
  144. },
  145. "function-hr": {
  146. append: "\n***\n",
  147. forceNewline: true
  148. },
  149. "function-table": {
  150. append: "\n" +
  151. "| Head | Head | Head |\n" +
  152. "| :--- | :--: | ---: |\n" +
  153. "| Cell | Cell | Cell |\n" +
  154. "| Cell | Cell | Cell |\n",
  155. forceNewline: true
  156. },
  157.  
  158. "function-clear": {
  159. exec: function(button, selText, commentForm, next) {
  160. commentForm.value = "";
  161. next("");
  162. }
  163. },
  164.  
  165. "function-snippets-tab": {
  166. exec: function(button, selText, commentForm, next) {
  167. next("\t");
  168. }
  169. },
  170. "function-snippets-useragent": {
  171. exec: function(button, selText, commentForm, next) {
  172. next("`" + navigator.userAgent + "`");
  173. }
  174. },
  175. "function-snippets-contributing": {
  176. exec: function(button, selText, commentForm, next) {
  177. next("Please, always consider reviewing the [guidelines for contributing](../blob/master/CONTRIBUTING.md) to this repository.");
  178. }
  179. },
  180.  
  181. "function-emoji": {
  182. exec: function(button, selText, commentForm, next) {
  183. next(":" + button.dataset.value + ":");
  184. }
  185. }
  186. };
  187. })();
  188.  
  189. var editorHTML = (function editorHTML() {
  190. return '<div id="gollum-editor-function-buttons" style="float: left;">' +
  191. ' <div class="button-group btn-group">' +
  192. ' <a href="#" id="function-bold" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Bold" style="height:26px;">' +
  193. ' <b style="font-weight: bolder;">B</b>' +
  194. ' </a>' +
  195. ' <a href="#" id="function-italic" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Italic">' +
  196. ' <em>i</em>' +
  197. ' </a>' +
  198. ' <a href="#" id="function-strikethrough" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Strikethrough">' +
  199. ' <s>S</s>' +
  200. ' </a>' +
  201. ' </div>' +
  202.  
  203. ' <div class="button-group btn-group">' +
  204. ' <div class="select-menu js-menu-container js-select-menu">' +
  205. ' <span class="btn btn-sm minibutton select-menu-button icon-only js-menu-target" aria-label="Headers" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  206. ' <span class="js-select-button">h#</span>' +
  207. ' </span>' +
  208. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container js-active-navigation-container" style="top: 26px;">' +
  209. ' <div class="select-menu-modal" style="width:auto; overflow:visible;">' +
  210. ' <div class="select-menu-header">' +
  211. ' <span class="select-menu-title">Choose header</span>' +
  212. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  213. ' </div>' +
  214. ' <div class="button-group btn-group">' +
  215. ' <a href="#" id="function-h1" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 1">' +
  216. ' <b class="select-menu-item-text js-select-button-text">h1</b>' +
  217. ' </a>' +
  218. ' <a href="#" id="function-h2" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 2">' +
  219. ' <b class="select-menu-item-text js-select-button-text">h2</b>' +
  220. ' </a>' +
  221. ' <a href="#" id="function-h3" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 3">' +
  222. ' <b class="select-menu-item-text js-select-button-text">h3</b>' +
  223. ' </a>' +
  224. ' <a href="#" id="function-h4" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 4">' +
  225. ' <b class="select-menu-item-text js-select-button-text">h4</b>' +
  226. ' </a>' +
  227. ' <a href="#" id="function-h5" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 5">' +
  228. ' <b class="select-menu-item-text js-select-button-text">h5</b>' +
  229. ' </a>' +
  230. ' <a href="#" id="function-h6" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 6">' +
  231. ' <b class="select-menu-item-text js-select-button-text">h6</b>' +
  232. ' </a>' +
  233. ' </div>' +
  234. ' </div>' +
  235. ' </div>' +
  236. ' </div>' +
  237. ' </div>' +
  238.  
  239. ' <div class="button-group btn-group">' +
  240. ' <a href="#" id="function-link" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Link">' +
  241. ' <span class="octicon octicon-link"></span>' +
  242. ' </a>' +
  243. ' <a href="#" id="function-image" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Image">' +
  244. ' <span class="octicon octicon-file-media"></span>' +
  245. ' </a>' +
  246. ' </div>' +
  247. ' <div class="button-group btn-group">' +
  248. ' <a href="#" id="function-ul" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Unordered List">' +
  249. ' <span class="octicon octicon-list-unordered"></span>' +
  250. ' </a>' +
  251. ' <a href="#" id="function-ol" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Ordered List">' +
  252. ' <span class="octicon octicon-list-ordered"></span>' +
  253. ' </a>' +
  254. ' <a href="#" id="function-checklist" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Task List">' +
  255. ' <span class="octicon octicon-checklist"></span>' +
  256. ' </a>' +
  257. ' </div>' +
  258.  
  259. ' <div class="button-group btn-group">' +
  260. ' <a href="#" id="function-code" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Code">' +
  261. ' <span class="octicon octicon-code"></span>' +
  262. ' </a>' +
  263. ' <a href="#" id="function-blockquote" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Blockquote">' +
  264. ' <span class="octicon octicon-quote"></span>' +
  265. ' </a>' +
  266. ' <a href="#" id="function-hr" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Horizontal Rule">' +
  267. ' <span class="octicon octicon-horizontal-rule"></span>' +
  268. ' </a>' +
  269. ' <a href="#" id="function-table" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Table">' +
  270. ' <span class="octicon octicon-three-bars"></span>' +
  271. ' </a>' +
  272. ' </div>' +
  273.  
  274. ' <div class="button-group btn-group">' +
  275. ' <div class="select-menu js-menu-container js-select-menu">' +
  276. ' <span class="btn btn-sm minibutton select-menu-button js-menu-target" aria-label="Snippets" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  277. ' <span class="octicon octicon-pin"></span>' +
  278. ' </span>' +
  279. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container js-active-navigation-container">' +
  280. ' <div class="select-menu-modal" style="overflow:visible;">' +
  281. ' <div class="select-menu-header">' +
  282. ' <span class="select-menu-title">Snippets</span>' +
  283. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  284. ' </div>' +
  285. ' <div class="select-menu-filters">' +
  286. ' <div class="select-menu-text-filter">' +
  287. ' <input type="text" placeholder="Filter snippets..." class="js-filterable-field js-navigation-enable" id="context-snippets-filter-field">' +
  288. ' </div>' +
  289. ' </div>' +
  290. ' <div class="select-menu-list" style="overflow:visible;">' +
  291. ' <div data-filterable-type="substring" data-filterable-for="context-snippets-filter-field">' +
  292. ' <a href="#" id="function-snippets-tab" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add tab character" style="table-layout:initial;">' +
  293. ' <span class="select-menu-item-text js-select-button-text">Add tab character</span>' +
  294. ' </a>' +
  295. ' <a href="#" id="function-snippets-useragent" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add UserAgent" style="table-layout:initial;">' +
  296. ' <span class="select-menu-item-text js-select-button-text">Add UserAgent</span>' +
  297. ' </a>' +
  298. ' <a href="#" id="function-snippets-contributing" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add contributing message" style="table-layout:initial;">' +
  299. ' <span class="select-menu-item-text">' +
  300. ' <span class="js-select-button-text">Contributing</span>' +
  301. ' <span class="description">Add contributing message</span>' +
  302. ' </span>' +
  303. ' </a>' +
  304. ' </div>' +
  305. ' <div class="select-menu-no-results">Nothing to show</div>' +
  306. ' </div>' +
  307. ' </div>' +
  308. ' </div>' +
  309. ' </div>' +
  310. ' </div>' +
  311.  
  312. ' <div class="button-group btn-group">' +
  313. ' <div class="select-menu js-menu-container js-select-menu">' +
  314. ' <span class="btn btn-sm minibutton select-menu-button js-menu-target" aria-label="Emoji" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  315. ' <span class="octicon octicon-octoface"></span>' +
  316. ' </span>' +
  317. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container js-active-navigation-container">' +
  318. ' <div class="select-menu-modal" style="overflow:visible;">' +
  319. ' <div class="select-menu-header">' +
  320. ' <span class="select-menu-title">Emoji</span>' +
  321. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  322. ' </div>' +
  323. ' <div class="select-menu-filters">' +
  324. ' <div class="select-menu-text-filter">' +
  325. ' <input type="text" placeholder="Filter emoji..." class="js-filterable-field js-navigation-enable" id="context-emoji-filter-field">' +
  326. ' </div>' +
  327. ' </div>' +
  328. ' <div class="suggester select-menu-list" style="overflow:visible;">' +
  329. ' <div class="select-menu-no-results">Nothing to show</div>' +
  330. ' </div>' +
  331. ' </div>' +
  332. ' </div>' +
  333. ' </div>' +
  334. ' </div>' +
  335.  
  336. '</div>' +
  337.  
  338. '<div style="float:right;">' +
  339. ' <a href="#" id="function-clear" class="btn btn-sm minibutton function-button tooltipped tooltipped-nw" aria-label="Clear">' +
  340. ' <span class="octicon octicon-circle-slash"></span>' +
  341. ' </a>' +
  342. '</div>';
  343. })();
  344.  
  345. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L516
  346. function executeAction(definitionObject, commentForm, button) {
  347. var txt = commentForm.value,
  348. selPos = {
  349. start: commentForm.selectionStart,
  350. end: commentForm.selectionEnd
  351. },
  352. selText = txt.substring(selPos.start, selPos.end),
  353. repText = selText,
  354. reselect = true,
  355. cursor = null;
  356.  
  357. // execute replacement function;
  358. if (definitionObject.exec) {
  359. definitionObject.exec(button, selText, commentForm, function(repText) {
  360. replaceFieldSelection(commentForm, repText);
  361. });
  362. return;
  363. }
  364.  
  365. // execute a search;
  366. var searchExp = new RegExp(definitionObject.search || /([^\n]+)/gi);
  367.  
  368. // replace text;
  369. if (definitionObject.replace) {
  370. var rt = definitionObject.replace;
  371. repText = repText.replace(searchExp, rt);
  372. repText = repText.replace(/\$[\d]/g, "");
  373. if (repText === "") {
  374. cursor = rt.indexOf("$1");
  375. repText = rt.replace(/\$[\d]/g, "");
  376. if (cursor === -1) {
  377. cursor = Math.floor(rt.length / 2);
  378. }
  379. }
  380. }
  381.  
  382. // append if necessary;
  383. if (definitionObject.append) {
  384. if (repText === selText) {
  385. reselect = false;
  386. }
  387. repText += definitionObject.append;
  388. }
  389.  
  390. if (repText) {
  391. if (definitionObject.forceNewline === true && (selPos.start > 0 && txt.substr(Math.max(0, selPos.start - 1), 1) !== "\n")) {
  392. repText = "\n" + repText;
  393. }
  394. replaceFieldSelection(commentForm, repText, reselect, cursor);
  395. }
  396. }
  397.  
  398. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L708
  399. function replaceFieldSelection(commentForm, replaceText, reselect, cursorOffset) {
  400. var txt = commentForm.value,
  401. selPos = {
  402. start: commentForm.selectionStart,
  403. end: commentForm.selectionEnd
  404. };
  405.  
  406. var selectNew = true;
  407. if (reselect === false) {
  408. selectNew = false;
  409. }
  410.  
  411. var scrollTop = null;
  412. if (commentForm.scrollTop) {
  413. scrollTop = commentForm.scrollTop;
  414. }
  415.  
  416. commentForm.value = txt.substring(0, selPos.start) + replaceText + txt.substring(selPos.end);
  417. commentForm.focus();
  418.  
  419. if (selectNew) {
  420. if (cursorOffset) {
  421. commentForm.setSelectionRange(selPos.start + cursorOffset, selPos.start + cursorOffset);
  422. } else {
  423. commentForm.setSelectionRange(selPos.start, selPos.start + replaceText.length);
  424. }
  425. }
  426.  
  427. if (scrollTop) {
  428. commentForm.scrollTop = scrollTop;
  429. }
  430. }
  431.  
  432. function isWiki() {
  433. return /\/wiki\//.test(location.href);
  434. }
  435.  
  436. function isGist() {
  437. return location.host === "gist.github.com";
  438. }
  439.  
  440. function overrideGollumMarkdown() {
  441. unsafeWindow.$.GollumEditor.defineLanguage("markdown", MarkDown);
  442. }
  443.  
  444. function unbindGollumFunctions() {
  445. window.setTimeout(function() {
  446. unsafeWindow.$(".function-button:not(#function-help)").unbind("click");
  447. }, 1);
  448. }
  449.  
  450. var functionButtonClick = function(e) {
  451. e.preventDefault();
  452. executeAction(MarkDown[this.id], this.commentForm, this);
  453. return false;
  454. };
  455.  
  456. function addSuggestions(commentForm) {
  457. var jssuggester = commentForm.parentNode.parentNode.querySelector(".js-suggester-container .js-suggester");
  458. var url = jssuggester.getAttribute("data-url");
  459. unsafeWindow.$.fetchText(url).then(function(suggestionsData) {
  460. suggestionsData = suggestionsData.replace(/js-navigation-item/g, "function-button js-navigation-item select-menu-item");
  461.  
  462. var suggestions = document.createElement("div");
  463. suggestions.innerHTML = suggestionsData;
  464.  
  465. var emojiSuggestions = suggestions.querySelector(".emoji-suggestions");
  466. emojiSuggestions.style.display = "block";
  467. emojiSuggestions.dataset.filterableType = "substring";
  468. emojiSuggestions.dataset.filterableFor = "context-emoji-filter-field";
  469. emojiSuggestions.dataset.filterableLimit = "10";
  470.  
  471. var suggester = commentForm.parentNode.querySelector(".suggester");
  472. suggester.style.display = "block";
  473. suggester.style.marginTop = "0";
  474. suggester.appendChild(emojiSuggestions);
  475. Array.prototype.forEach.call(suggester.querySelectorAll(".function-button"), function(button) {
  476. button.addEventListener("click", function(e) {
  477. e.preventDefault();
  478. executeAction(MarkDown["function-emoji"], commentForm, this);
  479. return false;
  480. });
  481. });
  482. });
  483. }
  484.  
  485. function addToolbar() {
  486. if (isWiki()) {
  487. // Override existing language with improved & missing functions and remove existing click events;
  488. overrideGollumMarkdown();
  489. unbindGollumFunctions();
  490.  
  491. // Remove existing click events when changing languages;
  492. document.getElementById("wiki_format").addEventListener("change", function() {
  493. unbindGollumFunctions();
  494.  
  495. Array.prototype.forEach.call(document.querySelectorAll(".comment-form-textarea .function-button"), function(button) {
  496. button.removeEventListener("click", functionButtonClick);
  497. });
  498. });
  499. }
  500.  
  501. Array.prototype.forEach.call(document.querySelectorAll(".comment-form-textarea,.js-comment-field"), function(commentForm) {
  502. var gollumEditor;
  503. if (commentForm.classList.contains("GithubCommentEnhancer")) {
  504. gollumEditor = commentForm.previousSibling;
  505. } else {
  506. commentForm.classList.add("GithubCommentEnhancer");
  507.  
  508. if (isWiki()) {
  509. gollumEditor = document.getElementById("gollum-editor-function-bar");
  510. var temp = document.createElement("div");
  511. temp.innerHTML = editorHTML;
  512. temp.firstElementChild.appendChild(document.getElementById("function-help")); // restore the help button;
  513. gollumEditor.replaceChild(temp.querySelector("#gollum-editor-function-buttons"), document.getElementById("gollum-editor-function-buttons"));
  514. Array.prototype.forEach.call(temp.children, function(elm) {
  515. elm.style.position = "absolute";
  516. elm.style.right = "30px";
  517. elm.style.top = "0";
  518. commentForm.parentNode.insertBefore(elm, commentForm);
  519. });
  520. temp = null;
  521. } else {
  522. gollumEditor = document.createElement("div");
  523. gollumEditor.innerHTML = editorHTML;
  524. gollumEditor.id = "gollum-editor-function-bar";
  525. gollumEditor.style.height = "26px";
  526. gollumEditor.style.margin = "10px 0";
  527. gollumEditor.classList.add("active");
  528. commentForm.parentNode.insertBefore(gollumEditor, commentForm);
  529. }
  530.  
  531. addSuggestions(commentForm);
  532.  
  533. var tabnavExtras = commentForm.parentNode.parentNode.querySelector(".comment-form-head .tabnav-right, .comment-form-head .right");
  534. if (tabnavExtras) {
  535. var sponsored = document.createElement("a");
  536. sponsored.setAttribute("target", "_blank");
  537. sponsored.setAttribute("href", "https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer");
  538. sponsored.classList.add("tabnav-widget", "text", "tabnav-extras", "tabnav-extra");
  539. var sponsoredIcon = document.createElement("span");
  540. sponsoredIcon.classList.add("octicon", "octicon-question");
  541. sponsored.appendChild(sponsoredIcon);
  542. sponsored.appendChild(document.createTextNode("Enhanced by Github Comment Enhancer"));
  543. tabnavExtras.insertBefore(sponsored, tabnavExtras.firstElementChild);
  544. }
  545. }
  546.  
  547. if (isGist()) {
  548. Array.prototype.forEach.call(gollumEditor.parentNode.querySelectorAll(".select-menu-button"), function(button) {
  549. button.style.paddingRight = "25px";
  550. });
  551. }
  552.  
  553. Array.prototype.forEach.call(gollumEditor.parentNode.querySelectorAll(".function-button"), function(button) {
  554. if (isGist() && button.classList.contains("minibutton")) {
  555. button.style.padding = "0px";
  556. button.style.textAlign = "center";
  557. button.style.width = "30px";
  558. button.firstElementChild.style.marginRight = "0px";
  559. }
  560. button.commentForm = commentForm; // remove event listener doesn't accept `bind`;
  561. button.addEventListener("click", functionButtonClick);
  562. });
  563. });
  564. }
  565.  
  566. // Source: https://github.com/domchristie/to-markdown
  567. // Code is altered with task list support: https://github.com/domchristie/to-markdown/pull/62
  568. var toMarkdown = function(string) {
  569.  
  570. var ELEMENTS = [{
  571. patterns: 'p',
  572. replacement: function(str, attrs, innerHTML) {
  573. return innerHTML ? '\n\n' + innerHTML + '\n' : '';
  574. }
  575. }, {
  576. patterns: 'br',
  577. type: 'void',
  578. replacement: ' \n'
  579. }, {
  580. patterns: 'h([1-6])',
  581. replacement: function(str, hLevel, attrs, innerHTML) {
  582. var hPrefix = '';
  583. for (var i = 0; i < hLevel; i++) {
  584. hPrefix += '#';
  585. }
  586. return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
  587. }
  588. }, {
  589. patterns: 'hr',
  590. type: 'void',
  591. replacement: '\n\n* * *\n'
  592. }, {
  593. patterns: 'a',
  594. replacement: function(str, attrs, innerHTML) {
  595. var href = attrs.match(attrRegExp('href')),
  596. title = attrs.match(attrRegExp('title'));
  597. return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
  598. }
  599. }, {
  600. patterns: ['b', 'strong'],
  601. replacement: function(str, attrs, innerHTML) {
  602. return innerHTML ? '**' + innerHTML + '**' : '';
  603. }
  604. }, {
  605. patterns: ['i', 'em'],
  606. replacement: function(str, attrs, innerHTML) {
  607. return innerHTML ? '_' + innerHTML + '_' : '';
  608. }
  609. }, {
  610. patterns: 'code',
  611. replacement: function(str, attrs, innerHTML) {
  612. return innerHTML ? '`' + innerHTML + '`' : '';
  613. }
  614. }, {
  615. patterns: 'img',
  616. type: 'void',
  617. replacement: function(str, attrs, innerHTML) {
  618. var src = attrs.match(attrRegExp('src')),
  619. alt = attrs.match(attrRegExp('alt')),
  620. title = attrs.match(attrRegExp('title'));
  621. return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
  622. }
  623. }];
  624.  
  625. for (var i = 0, len = ELEMENTS.length; i < len; i++) {
  626. if (typeof ELEMENTS[i].patterns === 'string') {
  627. string = replaceEls(string, {
  628. tag: ELEMENTS[i].patterns,
  629. replacement: ELEMENTS[i].replacement,
  630. type: ELEMENTS[i].type
  631. });
  632. } else {
  633. for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
  634. string = replaceEls(string, {
  635. tag: ELEMENTS[i].patterns[j],
  636. replacement: ELEMENTS[i].replacement,
  637. type: ELEMENTS[i].type
  638. });
  639. }
  640. }
  641. }
  642.  
  643. function replaceEls(html, elProperties) {
  644. var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
  645. regex = new RegExp(pattern, 'gi'),
  646. markdown = '';
  647. if (typeof elProperties.replacement === 'string') {
  648. markdown = html.replace(regex, elProperties.replacement);
  649. } else {
  650. markdown = html.replace(regex, function(str, p1, p2, p3) {
  651. return elProperties.replacement.call(this, str, p1, p2, p3);
  652. });
  653. }
  654. return markdown;
  655. }
  656.  
  657. function attrRegExp(attr) {
  658. return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
  659. }
  660.  
  661. // Pre code blocks
  662.  
  663. string = string.replace(/<pre\b[^>]*>`([\s\S]*?)`<\/pre>/gi, function(str, innerHTML) {
  664. var text = innerHTML;
  665. text = text.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense)
  666. text = text.replace(/\n/g, '\n ');
  667. return '\n\n ' + text + '\n';
  668. });
  669.  
  670. // Lists
  671.  
  672. // Escape numbers that could trigger an ol
  673. // If there are more than three spaces before the code, it would be in a pre tag
  674. // Make sure we are escaping the period not matching any character
  675. string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');
  676.  
  677. // Converts lists that have no child lists (of same type) first, then works its way up
  678. var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
  679. while (string.match(noChildrenRegex)) {
  680. string = string.replace(noChildrenRegex, function(str) {
  681. return replaceLists(str);
  682. });
  683. }
  684.  
  685. function replaceLists(html) {
  686.  
  687. html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) {
  688. var lis = innerHTML.split('</li>');
  689. lis.splice(lis.length - 1, 1);
  690.  
  691. for (i = 0, len = lis.length; i < len; i++) {
  692. if (lis[i]) {
  693. var prefix = (listType === 'ol') ? (i + 1) + ". " : "* ";
  694. lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) {
  695. innerHTML = innerHTML.replace(/\s*<input[^>]*?(checked[^>]*)?type=['"]?checkbox['"]?[^>]>/, function(inputStr, checked) {
  696. return checked ? '[X]' : '[ ]';
  697. });
  698. innerHTML = innerHTML.replace(/^\s+/, '');
  699. innerHTML = innerHTML.replace(/\n\n/g, '\n\n ');
  700. // indent nested lists
  701. innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 ');
  702. return prefix + innerHTML;
  703. });
  704. }
  705. lis[i] = lis[i].replace(/(.) +$/m, '$1');
  706. }
  707. return lis.join('\n');
  708. });
  709.  
  710. return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
  711. }
  712.  
  713. // Blockquotes
  714. var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
  715. while (string.match(deepest)) {
  716. string = string.replace(deepest, function(str) {
  717. return replaceBlockquotes(str);
  718. });
  719. }
  720.  
  721. function replaceBlockquotes(html) {
  722. html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) {
  723. inner = inner.replace(/^\s+|\s+$/g, '');
  724. inner = cleanUp(inner);
  725. inner = inner.replace(/^/gm, '> ');
  726. inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
  727. return inner;
  728. });
  729. return html;
  730. }
  731.  
  732. function cleanUp(string) {
  733. string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
  734. string = string.replace(/\n\s+\n/g, '\n\n');
  735. string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
  736. return string;
  737. }
  738.  
  739. return cleanUp(string);
  740. };
  741.  
  742. function addReplyButtons() {
  743. Array.prototype.forEach.call(document.querySelectorAll(".comment"), function(comment) {
  744. var oldReply = comment.querySelector(".GithubCommentEnhancerReply");
  745. if (oldReply) {
  746. oldReply.parentNode.removeChild(oldReply);
  747. }
  748.  
  749. var header = comment.querySelector(".timeline-comment-header"),
  750. actions = comment.querySelector(".timeline-comment-actions"),
  751. newComment = document.querySelector(".timeline-new-comment .comment-form-textarea");
  752.  
  753. if (!header) {
  754. return;
  755. }
  756. if (!actions) {
  757. actions = document.createElement("div");
  758. actions.classList.add("timeline-comment-actions");
  759. header.insertBefore(actions, header.firstElementChild);
  760. }
  761.  
  762. var reply = document.createElement("a");
  763. reply.setAttribute("href", "#");
  764. reply.setAttribute("aria-label", "Reply to this comment");
  765. reply.classList.add("GithubCommentEnhancerReply", "timeline-comment-action", "tooltipped", "tooltipped-ne");
  766. reply.addEventListener("click", function(e) {
  767. e.preventDefault();
  768.  
  769. var timestamp = comment.querySelector(".timestamp");
  770.  
  771. var commentText = comment.querySelector(".comment-form-textarea");
  772. if (commentText) {
  773. commentText = commentText.value;
  774. } else {
  775. commentText = toMarkdown(comment.querySelector(".comment-body").innerHTML);
  776. }
  777. commentText = commentText.trim().split("\n").map(function(line) {
  778. return "> " + line;
  779. }).join("\n");
  780.  
  781. var text = newComment.value.length > 0 ? "\n" : "";
  782. text += String.format('@{0} commented on [{1}]({2} "{3} - Replied by Github Comment Enhancer"):\n{4}\n\n',
  783. comment.querySelector(".author").textContent,
  784. timestamp.firstElementChild.getAttribute("title"),
  785. timestamp.href,
  786. timestamp.firstElementChild.getAttribute("datetime"),
  787. commentText);
  788.  
  789. newComment.value += text;
  790. newComment.setSelectionRange(newComment.value.length, newComment.value.length);
  791. newComment.focus();
  792. });
  793.  
  794. var replyIcon = document.createElement("span");
  795. replyIcon.classList.add("octicon", "octicon-mail-reply");
  796. reply.appendChild(replyIcon);
  797.  
  798. actions.appendChild(reply);
  799. });
  800. }
  801.  
  802. // init;
  803. function init() {
  804. addToolbar();
  805. addReplyButtons();
  806. }
  807. init();
  808.  
  809. // on pjax;
  810. unsafeWindow.$(document).on("pjax:end", init); // `pjax:end` also runs on history back;
  811.  
  812. // for inline comments;
  813. var files = document.querySelectorAll('.file-code');
  814. Array.prototype.forEach.call(files, function(file) {
  815. file = file.firstElementChild;
  816. new MutationObserver(function(mutations) {
  817. mutations.forEach(function(mutation) {
  818. if (mutation.target === file) {
  819. addToolbar();
  820. }
  821. });
  822. }).observe(file, {
  823. childList: true,
  824. subtree: true
  825. });
  826. });
  827.  
  828. })(typeof unsafeWindow !== "undefined" ? unsafeWindow : window);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址