Github Comment Enhancer

Enhances Github comments

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

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

QingJ © 2025

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