Github Comment Enhancer

Enhances Github comments

目前为 2015-09-11 提交的版本。查看 最新版本

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