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

QingJ © 2025

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