Github Comment Enhancer

Enhances Github comments

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

  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#readme
  10. // @homepageURL https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer#readme
  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.8.2
  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. text = isUrl ? "" : selTxt,
  102. href = isUrl ? selTxt : "";
  103. unsafeWindow.$.GollumDialog.init({
  104. title: "Insert Link",
  105. fields: [{
  106. id: "text",
  107. name: "Link Text",
  108. type: "text",
  109. value: text
  110. }, {
  111. id: "href",
  112. name: "URL",
  113. type: "text",
  114. value: href
  115. }],
  116. OK: function(t) {
  117. if (t.href) {
  118. next(String.format("[{0}]({1}){2}",
  119. t.text || t.href,
  120. t.href, (/\s+$/.test(selText) ? " " : "")));
  121. }
  122. }
  123. });
  124. },
  125. shortcut: "ctrl+l"
  126. },
  127. "function-image": {
  128. exec: function(button, selText, commentForm, next) {
  129. var selTxt = selText.trim(),
  130. isUrl = selTxt && /(?:https?:\/\/)|(?:www\.)/.test(selTxt),
  131. url = isUrl ? selTxt : "",
  132. alt = isUrl ? "" : selTxt;
  133. unsafeWindow.$.GollumDialog.init({
  134. title: "Insert Image",
  135. fields: [{
  136. id: "url",
  137. name: "Image URL",
  138. type: "text",
  139. value: url
  140. }, {
  141. id: "alt",
  142. name: "Alt Text",
  143. type: "text",
  144. value: alt
  145. }],
  146. OK: function(t) {
  147. if (t.url) {
  148. next(String.format("![{0}]({1}){2}",
  149. t.alt || t.url,
  150. t.url, (/\s+$/.test(selText) ? " " : "")));
  151. }
  152. }
  153. });
  154. },
  155. shortcut: "ctrl+g"
  156. },
  157.  
  158. "function-ul": {
  159. search: /(.+)([\n]?)/g,
  160. replace: String.format("{0} $1$2", listCharacter),
  161. forceNewline: true,
  162. shortcut: "alt+ctrl+u"
  163. },
  164. "function-ol": {
  165. exec: function(button, selText, commentForm, next) {
  166. var repText = "";
  167. if (!selText) {
  168. repText = "1. ";
  169. } else {
  170. var lines = selText.split("\n"),
  171. hasContent = /[\w]+/;
  172. for (var i = 0; i < lines.length; i++) {
  173. if (hasContent.test(lines[i])) {
  174. repText += String.format("{0}. {1}\n", i + 1, lines[i]);
  175. }
  176. }
  177. }
  178. next(repText);
  179. },
  180. shortcut: "alt+ctrl+o"
  181. },
  182. "function-checklist": {
  183. search: /(.+)([\n]?)/g,
  184. replace: String.format("{0} [ ] $1$2", listCharacter),
  185. forceNewline: true,
  186. shortcut: "alt+ctrl+t"
  187. },
  188.  
  189. "function-code": {
  190. exec: function(button, selText, commentForm, next) {
  191. var rt = selText.indexOf("\n") > -1 ? "$1\n```\n$2\n```$3" : "$1`$2`$3";
  192. next(selText.replace(/^(\s*)([\s\S]*?)(\s*)$/g, rt));
  193. },
  194. shortcut: "ctrl+k"
  195. },
  196. "function-code-syntax": {
  197. exec: function(button, selText, commentForm, next) {
  198. var rt = "$1\n```" + button.dataset.value + "\n$2\n```$3";
  199. next(selText.replace(/^(\s*)([\s\S]*?)(\s*)$/g, rt));
  200. }
  201. },
  202.  
  203. "function-blockquote": {
  204. search: /(.+)([\n]?)/g,
  205. replace: "> $1$2",
  206. forceNewline: true,
  207. shortcut: "ctrl+q"
  208. },
  209. "function-rule": {
  210. append: String.format("\n{0}\n", lineCharacter),
  211. forceNewline: true,
  212. shortcut: "ctrl+r"
  213. },
  214. "function-table": {
  215. append: "\n" +
  216. "| Head | Head | Head |\n" +
  217. "| :--- | :----: | ----: |\n" +
  218. "| Cell | Cell | Cell |\n" +
  219. "| Left | Center | Right |\n",
  220. forceNewline: true,
  221. shortcut: "alt+shift+t"
  222. },
  223.  
  224. "function-clear": {
  225. exec: function(button, selText, commentForm, next) {
  226. commentForm.value = "";
  227. next("");
  228. },
  229. shortcut: "alt+ctrl+x"
  230. },
  231.  
  232. "function-snippets-tab": {
  233. exec: function(button, selText, commentForm, next) {
  234. next("\t");
  235. }
  236. },
  237. "function-snippets-useragent": {
  238. exec: function(button, selText, commentForm, next) {
  239. next("`" + navigator.userAgent + "`");
  240. }
  241. },
  242. "function-snippets-contributing": {
  243. exec: function(button, selText, commentForm, next) {
  244. next("Please, always consider reviewing the [guidelines for contributing](../blob/master/CONTRIBUTING.md) to this repository.");
  245. }
  246. },
  247.  
  248. "function-emoji": {
  249. exec: function(button, selText, commentForm, next) {
  250. next(button.dataset.value);
  251. }
  252. }
  253. };
  254. })();
  255.  
  256. var toolBarLeftHTML =
  257. '<div id="gollum-editor-function-buttons" style="float: left;">' +
  258.  
  259. /* Bold, italic, underline & Strikethrough; */
  260. ' <div class="button-group btn-group">' +
  261. ' <a href="#" id="function-bold" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Bold (ctrl+b)">' +
  262. ' <b style="font-weight: bolder;">B</b>' +
  263. ' </a>' +
  264. ' <a href="#" id="function-italic" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Italic (ctrl+i)">' +
  265. ' <em>i</em>' +
  266. ' </a>' +
  267. ' <a href="#" id="function-underline" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Underline (ctrl+u)">' +
  268. ' <ins>U</ins>' +
  269. ' </a>' +
  270. ' <a href="#" id="function-strikethrough" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Strikethrough (ctrl+s)">' +
  271. ' <s>S</s>' +
  272. ' </a>' +
  273. ' </div>' +
  274.  
  275. /* Headers (1 - 6); */
  276. ' <div class="button-group btn-group">' +
  277. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Headers">' +
  278. ' <a id="function-h1" class="btn btn-sm minibutton select-menu-button icon-only js-menu-target function-button function-dummy" aria-label="Headers" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  279. ' <span class="js-select-button">h#</span>' +
  280. ' </a>' +
  281. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  282. ' <div class="select-menu-modal" style="width:auto; overflow:visible;">' +
  283. ' <div class="select-menu-header">' +
  284. ' <span class="select-menu-title">Choose header</span>' +
  285. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  286. ' </div>' +
  287. ' <div class="button-group btn-group" style="min-width:175px;">' +
  288. ' <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)">' +
  289. ' <b class="select-menu-item-text js-select-button-text">h1</b>' +
  290. ' </a>' +
  291. ' <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)">' +
  292. ' <b class="select-menu-item-text js-select-button-text">h2</b>' +
  293. ' </a>' +
  294. ' <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)">' +
  295. ' <b class="select-menu-item-text js-select-button-text">h3</b>' +
  296. ' </a>' +
  297. ' <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)">' +
  298. ' <b class="select-menu-item-text js-select-button-text">h4</b>' +
  299. ' </a>' +
  300. ' <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)">' +
  301. ' <b class="select-menu-item-text js-select-button-text">h5</b>' +
  302. ' </a>' +
  303. ' <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)">' +
  304. ' <b class="select-menu-item-text js-select-button-text">h6</b>' +
  305. ' </a>' +
  306. ' </div>' +
  307. ' </div>' +
  308. ' </div>' +
  309. ' </div>' +
  310. ' </div>' +
  311.  
  312. /* Link & image; */
  313. ' <div class="button-group btn-group">' +
  314. ' <a href="#" id="function-link" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Link (ctrl+l)">' +
  315. ' <span class="octicon octicon-link"></span>' +
  316. ' </a>' +
  317. ' <a href="#" id="function-image" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Image (ctrl+g)">' +
  318. ' <span class="octicon octicon-file-media"></span>' +
  319. ' </a>' +
  320. ' </div>' +
  321.  
  322. /* Lists (unordered, ordered & task); */
  323. ' <div class="button-group btn-group">' +
  324. ' <a href="#" id="function-ul" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Unordered List (alt+ctrl+u)">' +
  325. ' <span class="octicon octicon-list-unordered"></span>' +
  326. ' </a>' +
  327. ' <a href="#" id="function-ol" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Ordered List (alt+ctrl+o)">' +
  328. ' <span class="octicon octicon-list-ordered"></span>' +
  329. ' </a>' +
  330. ' <a href="#" id="function-checklist" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Task List (alt+ctrl+t)">' +
  331. ' <span class="octicon octicon-checklist"></span>' +
  332. ' </a>' +
  333. ' </div>' +
  334.  
  335. /* Code (syntax); */
  336. ' <div class="button-group btn-group">' +
  337. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Code (ctrl+k)">' +
  338. ' <a href="#" id="function-code" class="btn btn-sm minibutton function-button">' +
  339. ' <span class="octicon octicon-code"></span>' +
  340. ' </a>' +
  341. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  342. ' <div class="select-menu-modal" style="overflow:visible;">' +
  343. ' <div class="select-menu-header">' +
  344. ' <span class="select-menu-title">Code syntax</span>' +
  345. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  346. ' </div>' +
  347. ' <div class="select-menu-filters">' +
  348. ' <div class="select-menu-text-filter">' +
  349. ' <input type="text" placeholder="Filter code syntax..." class="js-filterable-field js-navigation-enable" id="context-code-syntax-filter-field">' +
  350. ' </div>' +
  351. ' </div>' +
  352. ' <div class="code-syntaxes select-menu-list" style="overflow:visible;">' +
  353. ' <div class="select-menu-no-results">Nothing to show</div>' +
  354. ' </div>' +
  355. ' </div>' +
  356. ' </div>' +
  357. ' <a href="#" id="function-code" class="btn btn-sm minibutton select-menu-button js-menu-target function-button function-dummy" style="width:20px; margin-left:-1px;"></a>' +
  358. ' </div>' +
  359. ' </div>' +
  360.  
  361. /* Blockquote, horizontal rule & table; */
  362. ' <div class="button-group btn-group">' +
  363. ' <a href="#" id="function-blockquote" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Blockquote (ctrl+q)">' +
  364. ' <span class="octicon octicon-quote"></span>' +
  365. ' </a>' +
  366. ' <a href="#" id="function-rule" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Horizontal Rule (ctrl+r)">' +
  367. ' <span class="octicon octicon-horizontal-rule"></span>' +
  368. ' </a>' +
  369. ' <a href="#" id="function-table" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Table (alt+shift+t)">' +
  370. ' <span class="octicon octicon-three-bars"></span>' +
  371. ' </a>' +
  372. ' </div>' +
  373.  
  374. /* Snippets; */
  375. ' <div class="button-group btn-group">' +
  376. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Snippets">' +
  377. ' <a href="#" 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;">' +
  378. ' <span class="octicon octicon-pin"></span>' +
  379. ' </a>' +
  380. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  381. ' <div class="select-menu-modal" style="overflow:visible;">' +
  382. ' <div class="select-menu-header">' +
  383. ' <span class="select-menu-title">Snippets</span>' +
  384. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  385. ' </div>' +
  386. ' <div class="select-menu-filters">' +
  387. ' <div class="select-menu-text-filter">' +
  388. ' <input type="text" placeholder="Filter snippets..." class="js-filterable-field js-navigation-enable" id="context-snippets-filter-field">' +
  389. ' </div>' +
  390. ' </div>' +
  391. ' <div class="select-menu-list" style="overflow:visible;">' +
  392. ' <div data-filterable-type="substring" data-filterable-for="context-snippets-filter-field">' +
  393. ' <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;">' +
  394. ' <span class="select-menu-item-text js-select-button-text">Add tab character</span>' +
  395. ' </a>' +
  396. ' <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;">' +
  397. ' <span class="select-menu-item-text js-select-button-text">Add UserAgent</span>' +
  398. ' </a>' +
  399. ' <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;">' +
  400. ' <span class="select-menu-item-text">' +
  401. ' <span class="js-select-button-text">Contributing</span>' +
  402. ' <span class="description">Add contributing message</span>' +
  403. ' </span>' +
  404. ' </a>' +
  405. ' </div>' +
  406. ' <div class="select-menu-no-results">Nothing to show</div>' +
  407. ' </div>' +
  408. ' </div>' +
  409. ' </div>' +
  410. ' </div>' +
  411. ' </div>' +
  412.  
  413. /* Emoji; */
  414. ' <div class="button-group btn-group suggester-function">' +
  415. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Emoji">' +
  416. ' <a href="#" 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;">' +
  417. ' <span class="octicon octicon-octoface"></span>' +
  418. ' </a>' +
  419. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  420. ' <div class="select-menu-modal" style="overflow:visible;">' +
  421. ' <div class="select-menu-header">' +
  422. ' <span class="select-menu-title">Emoji</span>' +
  423. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  424. ' </div>' +
  425. ' <div class="select-menu-filters">' +
  426. ' <div class="select-menu-text-filter">' +
  427. ' <input type="text" placeholder="Filter emoji..." class="js-filterable-field js-navigation-enable" id="context-emoji-filter-field">' +
  428. ' </div>' +
  429. ' </div>' +
  430. ' <div class="suggester select-menu-list" style="overflow:visible;">' +
  431. ' <div class="select-menu-no-results">Nothing to show</div>' +
  432. ' </div>' +
  433. ' </div>' +
  434. ' </div>' +
  435. ' </div>' +
  436. ' </div>' +
  437.  
  438. '</div>';
  439. var toolBarRightHTML =
  440. /* Clear; */
  441. '<div style="float:right;">' +
  442. ' <div class="button-group btn-group">' +
  443. ' <span id="function-clear" class="btn btn-sm minibutton function-button tooltipped tooltipped-nw" aria-label="Clear (alt+ctrl+x)">' +
  444. ' <span class="octicon octicon-trashcan"></span>' +
  445. ' </span>' +
  446. ' </div>' +
  447. '</div>';
  448.  
  449. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L516
  450. function executeAction(definitionObject, commentForm, button) {
  451. var txt = commentForm.value,
  452. selPos = {
  453. start: commentForm.selectionStart,
  454. end: commentForm.selectionEnd
  455. },
  456. selText = txt.substring(selPos.start, selPos.end),
  457. repText = selText,
  458. reselect = true,
  459. cursor = null;
  460.  
  461. // execute replacement function;
  462. if (definitionObject.exec) {
  463. definitionObject.exec(button, selText, commentForm, function(repText) {
  464. replaceFieldSelection(commentForm, repText);
  465. });
  466. return;
  467. }
  468.  
  469. // execute a search;
  470. var searchExp = new RegExp(definitionObject.search || /([^\n]+)/gi);
  471.  
  472. // replace text;
  473. if (definitionObject.replace) {
  474. var rt = definitionObject.replace;
  475. repText = repText.replace(searchExp, rt);
  476. repText = repText.replace(/\$[\d]/g, "");
  477. if (repText === "") {
  478. cursor = rt.indexOf("$1");
  479. repText = rt.replace(/\$[\d]/g, "");
  480. if (cursor === -1) {
  481. cursor = Math.floor(rt.length / 2);
  482. }
  483. }
  484. }
  485.  
  486. // append if necessary;
  487. if (definitionObject.append) {
  488. if (repText === selText) {
  489. reselect = false;
  490. }
  491. repText += definitionObject.append;
  492. }
  493.  
  494. if (repText) {
  495. if (definitionObject.forceNewline === true && (selPos.start > 0 && txt.substr(Math.max(0, selPos.start - 1), 1) !== "\n")) {
  496. repText = "\n" + repText;
  497. }
  498. replaceFieldSelection(commentForm, repText, reselect, cursor);
  499. }
  500. }
  501.  
  502. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L708
  503. function replaceFieldSelection(commentForm, replaceText, reselect, cursorOffset) {
  504. var txt = commentForm.value,
  505. selPos = {
  506. start: commentForm.selectionStart,
  507. end: commentForm.selectionEnd
  508. };
  509.  
  510. var selectNew = true;
  511. if (reselect === false) {
  512. selectNew = false;
  513. }
  514.  
  515. var scrollTop = null;
  516. if (commentForm.scrollTop) {
  517. scrollTop = commentForm.scrollTop;
  518. }
  519.  
  520. commentForm.value = txt.substring(0, selPos.start) + replaceText + txt.substring(selPos.end);
  521. commentForm.focus();
  522.  
  523. if (selectNew) {
  524. if (cursorOffset) {
  525. commentForm.setSelectionRange(selPos.start + cursorOffset, selPos.start + cursorOffset);
  526. } else {
  527. commentForm.setSelectionRange(selPos.start, selPos.start + replaceText.length);
  528. }
  529. }
  530.  
  531. if (scrollTop) {
  532. commentForm.scrollTop = scrollTop;
  533. }
  534. }
  535.  
  536. function isWiki() {
  537. return /\/wiki\//.test(location.href);
  538. }
  539.  
  540. function isGist() {
  541. return "gist.github.com" === location.host;
  542. }
  543.  
  544. function overrideGollumMarkdown() {
  545. unsafeWindow.$.GollumEditor.defineLanguage("markdown", MarkDown);
  546. }
  547.  
  548. function unbindGollumFunctions() {
  549. window.setTimeout(function() {
  550. unsafeWindow.$(".function-button:not(#function-help)").unbind("click");
  551. }, 1);
  552. }
  553.  
  554. var buttonEvent = function(e) {
  555. if (!this.classList.contains("disabled") && !this.classList.contains("function-dummy")) {
  556. e.preventDefault();
  557. executeAction(MarkDown[this.id], this.commentForm, this);
  558. return false;
  559. }
  560. };
  561.  
  562. // The suggester container needs extra margin to move the menu below the text because of the added toolbar.
  563. function fixSuggesterMenu(commentForm) {
  564. commentForm.parentNode.parentNode.querySelector(".suggester-container").style.marginTop = "36px";
  565. }
  566.  
  567. var codeSyntaxTop = ["JavaScript", "Java", "Ruby", "PHP", "Python", "CSS", "C++", "C#", "C", "HTML"]; // https://github.com/blog/2047-language-trends-on-github
  568. var codeSyntaxList = ["ABAP", "abl", "aconf", "ActionScript", "actionscript 3",
  569. "actionscript3", "Ada", "ada2005", "ada95", "advpl", "Agda", "ags",
  570. "AGS Script", "ahk", "Alloy", "AMPL", "Ant Build System", "ANTLR",
  571. "apache", "ApacheConf", "Apex", "API Blueprint", "APL", "AppleScript",
  572. "Arc", "Arduino", "as3", "AsciiDoc", "ASP", "AspectJ", "aspx",
  573. "aspx-vb", "Assembly", "ATS", "ats2", "au3", "Augeas", "AutoHotkey",
  574. "AutoIt", "AutoIt3", "AutoItScript", "Awk", "b3d", "bash",
  575. "bash session", "bat", "batch", "Batchfile", "Befunge", "Bison",
  576. "BitBake", "blitz3d", "BlitzBasic", "BlitzMax", "blitzplus",
  577. "Bluespec", "bmax", "Boo", "bplus", "Brainfuck", "Brightscript", "Bro",
  578. "bsdmake", "byond", "C", "C#", "C++", "c++-objdumb", "C-ObjDump",
  579. "c2hs", "C2hs Haskell", "Cap'n Proto", "Carto", "CartoCSS", "Ceylon",
  580. "cfc", "cfm", "cfml", "Chapel", "Charity", "chpl", "ChucK", "Cirru",
  581. "Clarion", "Clean", "clipper", "CLIPS", "Clojure", "CMake", "COBOL",
  582. "coffee", "coffee-script", "CoffeeScript", "ColdFusion",
  583. "ColdFusion CFC", "coldfusion html", "Common Lisp", "Component Pascal",
  584. "console", "Cool", "Coq", "cpp", "Cpp-ObjDump", "Creole", "Crystal",
  585. "csharp", "CSS", "Cucumber", "Cuda", "Cycript", "Cython", "D",
  586. "D-ObjDump", "Darcs Patch", "Dart", "dcl", "delphi", "desktop", "Diff",
  587. "DIGITAL Command Language", "DM", "DNS Zone", "Dockerfile",
  588. "Dogescript", "dosbatch", "dosini", "dpatch", "DTrace",
  589. "dtrace-script", "Dylan", "E", "Eagle", "eC", "Ecere Projects", "ECL",
  590. "ECLiPSe", "edn", "Eiffel", "elisp", "Elixir", "Elm", "emacs",
  591. "Emacs Lisp", "EmberScript", "erb", "Erlang", "F#", "Factor", "Fancy",
  592. "Fantom", "Filterscript", "fish", "flex", "FLUX", "Formatted", "Forth",
  593. "FORTRAN", "foxpro", "Frege", "fsharp", "fundamental", "G-code",
  594. "Game Maker Language", "GAMS", "GAP", "GAS", "GDScript", "Genshi",
  595. "Gentoo Ebuild", "Gentoo Eclass", "Gettext Catalog", "gf", "gherkin",
  596. "GLSL", "Glyph", "Gnuplot", "Go", "Golo", "Gosu", "Grace", "Gradle",
  597. "Grammatical Framework", "Graph Modeling Language", "Graphviz (DOT)",
  598. "Groff", "Groovy", "Groovy Server Pages", "gsp", "Hack", "Haml",
  599. "Handlebars", "Harbour", "Haskell", "Haxe", "hbs", "HCL", "HTML",
  600. "HTML+Django", "html+django/jinja", "HTML+ERB", "html+jinja",
  601. "HTML+PHP", "html+ruby", "htmlbars", "htmldjango", "HTTP", "Hy",
  602. "hylang", "HyPhy", "i7", "IDL", "Idris", "igor", "IGOR Pro", "igorpro",
  603. "inc", "Inform 7", "inform7", "INI", "Inno Setup", "Io", "Ioke", "irc",
  604. "IRC log", "irc logs", "Isabelle", "Isabelle ROOT", "J", "Jade",
  605. "Jasmin", "Java", "java server page", "Java Server Pages",
  606. "JavaScript", "JFlex", "jruby", "js", "JSON", "JSON5", "JSONiq",
  607. "JSONLD", "jsp", "JSX", "Julia", "KiCad", "Kit", "Kotlin", "KRL",
  608. "LabVIEW", "Lasso", "lassoscript", "latex", "Latte", "Lean", "Less",
  609. "Lex", "LFE", "lhaskell", "lhs", "LilyPond", "Limbo", "Linker Script",
  610. "Linux Kernel Module", "Liquid", "lisp", "litcoffee", "Literate Agda",
  611. "Literate CoffeeScript", "Literate Haskell", "live-script",
  612. "LiveScript", "LLVM", "Logos", "Logtalk", "LOLCODE", "LookML",
  613. "LoomScript", "ls", "LSL", "Lua", "M", "macruby", "make", "Makefile",
  614. "Mako", "Markdown", "Mask", "Mathematica", "Matlab", "Maven POM",
  615. "Max", "max/msp", "maxmsp", "MediaWiki", "Mercury", "mf", "MiniD",
  616. "Mirah", "mma", "Modelica", "Modula-2", "Module Management System",
  617. "Monkey", "Moocode", "MoonScript", "MTML", "MUF", "mumps", "mupad",
  618. "Myghty", "nasm", "NCL", "Nemerle", "nesC", "NetLinx", "NetLinx+ERB",
  619. "NetLogo", "NewLisp", "Nginx", "nginx configuration file", "Nimrod",
  620. "Ninja", "Nit", "Nix", "nixos", "NL", "node", "nroff", "NSIS", "Nu",
  621. "NumPy", "nush", "nvim", "obj-c", "obj-c++", "obj-j", "objc", "objc++",
  622. "ObjDump", "Objective-C", "Objective-C++", "Objective-J", "objectivec",
  623. "objectivec++", "objectivej", "objectpascal", "objj", "OCaml",
  624. "Omgrofl", "ooc", "Opa", "Opal", "OpenCL", "openedge", "OpenEdge ABL",
  625. "OpenSCAD", "Org", "osascript", "Ox", "Oxygene", "Oz", "Pan",
  626. "Papyrus", "Parrot", "Parrot Assembly",
  627. "Parrot Internal Representation", "Pascal", "pasm", "PAWN", "Perl",
  628. "Perl6", "PHP", "PicoLisp", "PigLatin", "Pike", "pir", "PLpgSQL",
  629. "PLSQL", "Pod", "PogoScript", "posh", "postscr", "PostScript", "pot",
  630. "PowerShell", "Processing", "progress", "Prolog", "Propeller Spin",
  631. "protobuf", "Protocol Buffer", "Protocol Buffers", "Public Key",
  632. "Puppet", "Pure Data", "PureBasic", "PureScript", "pyrex", "Python",
  633. "Python traceback", "QMake", "QML", "R", "Racket",
  634. "Ragel in Ruby Host", "ragel-rb", "ragel-ruby", "rake", "RAML", "raw",
  635. "Raw token data", "rb", "rbx", "RDoc", "REALbasic", "Rebol", "Red",
  636. "red/system", "Redcode", "RenderScript", "reStructuredText", "RHTML",
  637. "RMarkdown", "RobotFramework", "Rouge", "Rscript", "rss", "rst",
  638. "Ruby", "Rust", "rusthon", "Sage", "salt", "SaltStack", "saltstate",
  639. "SAS", "Sass", "Scala", "Scaml", "Scheme", "Scilab", "SCSS", "Self",
  640. "sh", "Shell", "ShellSession", "Shen", "Slash", "Slim", "Smali",
  641. "Smalltalk", "Smarty", "sml", "SMT", "sourcemod", "SourcePawn",
  642. "SPARQL", "splus", "SQF", "SQL", "SQLPL", "squeak", "Squirrel",
  643. "Standard ML", "Stata", "STON", "Stylus", "SuperCollider", "SVG",
  644. "Swift", "SystemVerilog", "Tcl", "Tcsh", "Tea", "TeX", "Text",
  645. "Textile", "Thrift", "TOML", "ts", "Turing", "Turtle", "Twig", "TXL",
  646. "TypeScript", "udiff", "Unified Parallel C", "Unity3D Asset",
  647. "UnrealScript", "Vala", "vb.net", "vbnet", "VCL", "Verilog", "VHDL",
  648. "vim", "VimL", "Visual Basic", "Volt", "Vue", "Web Ontology Language",
  649. "WebIDL", "winbatch", "wisp", "wsdl", "X10", "xBase", "XC", "xhtml",
  650. "XML", "xml+genshi", "xml+kid", "Xojo", "XPages", "XProc", "XQuery",
  651. "XS", "xsd", "xsl", "XSLT", "xten", "Xtend", "Yacc", "YAML", "yml",
  652. "Zephir", "Zimpl", "zsh"
  653. ]; // https://github.com/jerone/UserScripts/issues/18
  654. var codeSyntaxes = [].concat(codeSyntaxTop, codeSyntaxList).filter(function(a, b, c) {
  655. return c.indexOf(a) === b;
  656. });
  657.  
  658. function addCodeSyntax(commentForm) {
  659. var syntaxSuggestions = document.createElement("div");
  660. syntaxSuggestions.dataset.filterableType = "substring";
  661. syntaxSuggestions.dataset.filterableFor = "context-code-syntax-filter-field";
  662. syntaxSuggestions.dataset.filterableLimit = codeSyntaxTop.length; // Show top code syntaxes on open;
  663.  
  664. codeSyntaxes.forEach(function(syntax) {
  665. var syntaxSuggestion = document.createElement("a");
  666. syntaxSuggestion.setAttribute("href", "#");
  667. syntaxSuggestion.classList.add("function-button", "select-menu-item", "js-navigation-item");
  668. syntaxSuggestion.dataset.value = syntax;
  669. syntaxSuggestion.id = "function-code-syntax";
  670. syntaxSuggestions.appendChild(syntaxSuggestion);
  671.  
  672. var syntaxSuggestionText = document.createElement("span");
  673. syntaxSuggestionText.classList.add("select-menu-item-text", "js-select-button-text");
  674. syntaxSuggestionText.appendChild(document.createTextNode(syntax));
  675. syntaxSuggestion.appendChild(syntaxSuggestionText);
  676. });
  677.  
  678. var suggester = commentForm.parentNode.parentNode.querySelector(".code-syntaxes");
  679. suggester.appendChild(syntaxSuggestions);
  680. }
  681.  
  682. var suggestionsCache = {};
  683.  
  684. function addSuggestions(commentForm) {
  685. var jssuggester = commentForm.parentNode.parentNode.querySelector(".suggester-container .suggester");
  686. var url = jssuggester.getAttribute("data-url");
  687.  
  688. if (suggestionsCache[url]) {
  689. parseSuggestions(commentForm, suggestionsCache[url]);
  690. } else {
  691. unsafeWindow.$.ajax({
  692. url: url,
  693. success: function(suggestionsData) {
  694. suggestionsCache[url] = suggestionsData;
  695. parseSuggestions(commentForm, suggestionsData);
  696. }
  697. });
  698. }
  699. }
  700.  
  701. function parseSuggestions(commentForm, suggestionsData) {
  702. suggestionsData = suggestionsData.replace(/js-navigation-item/g,
  703. "function-button js-navigation-item select-menu-item");
  704.  
  705. var suggestions = document.createElement("div");
  706. suggestions.innerHTML = suggestionsData;
  707.  
  708. var emojiSuggestions = suggestions.querySelector(".emoji-suggestions");
  709. emojiSuggestions.style.display = "block";
  710. emojiSuggestions.dataset.filterableType = "substring";
  711. emojiSuggestions.dataset.filterableFor = "context-emoji-filter-field";
  712. emojiSuggestions.dataset.filterableLimit = "10";
  713.  
  714. var suggester = commentForm.parentNode.parentNode.querySelector(".suggester");
  715. suggester.style.display = "block";
  716. suggester.style.marginTop = "0";
  717. suggester.appendChild(emojiSuggestions);
  718.  
  719. var buttons = suggester.querySelectorAll(".function-button");
  720. Array.prototype.forEach.call(buttons, function(button) {
  721. button.commentForm = commentForm;
  722. button.id = "function-emoji";
  723. button.addEventListener("click", buttonEvent, false);
  724. unsafeWindow.$(button).on("navigation:keydown", function(e) {
  725. if (e.hotkey === "enter") {
  726. buttonEvent.call(this, e);
  727. }
  728. });
  729. });
  730. }
  731.  
  732. function addSponsorLink(commentForm) {
  733. var tabnavExtras = commentForm.parentNode.parentNode.querySelector(".comment-form-head .tabnav-right, .comment-form-head .right");
  734. if (tabnavExtras) {
  735. var elem = commentForm;
  736. while ((elem = elem.parentNode) && elem.nodeType !== 9 && !elem.classList.contains("timeline-inline-comments")) {}
  737. var sponsoredText = elem !== document ? " Github Comment Enhancer" : " Enhanced by Github Comment Enhancer";
  738. var sponsored = document.createElement("a");
  739. sponsored.setAttribute("target", "_blank");
  740. sponsored.setAttribute("href", "https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer#readme");
  741. sponsored.classList.add("tabnav-widget", "text", "tabnav-extras", "tabnav-extra");
  742. var sponsoredIcon = document.createElement("span");
  743. sponsoredIcon.classList.add("octicon", "octicon-question");
  744. sponsored.appendChild(sponsoredIcon);
  745. sponsored.appendChild(document.createTextNode(sponsoredText));
  746. tabnavExtras.insertBefore(sponsored, tabnavExtras.firstElementChild);
  747. }
  748. }
  749.  
  750. function commentFormKeyEvent(commentForm, e) {
  751. var keys = [];
  752. if (e.altKey) {
  753. keys.push('alt');
  754. }
  755. if (e.ctrlKey) {
  756. keys.push('ctrl');
  757. }
  758. if (e.shiftKey) {
  759. keys.push('shift');
  760. }
  761. keys.push(String.fromCharCode(e.which).toLowerCase());
  762. var keyCombination = keys.join('+');
  763.  
  764. var action;
  765. for (var actionName in MarkDown) {
  766. if (MarkDown[actionName].shortcut && MarkDown[actionName].shortcut.toLowerCase() === keyCombination) {
  767. action = MarkDown[actionName];
  768. break;
  769. }
  770. }
  771. if (action) {
  772. e.preventDefault();
  773. e.stopPropagation();
  774. executeAction(action, commentForm, null);
  775. return false;
  776. }
  777. }
  778.  
  779. function addToolbar() {
  780. if (isWiki()) {
  781. // Override existing language with improved & missing functions and remove existing click events;
  782. overrideGollumMarkdown();
  783. unbindGollumFunctions();
  784.  
  785. // Remove existing click events when changing languages;
  786. document.getElementById("wiki_format").addEventListener("change", function() {
  787. unbindGollumFunctions();
  788.  
  789. var buttons = document.querySelectorAll(".comment-form-textarea .function-button");
  790. Array.prototype.forEach.call(buttons, function(button) {
  791. button.removeEventListener("click", buttonEvent);
  792. });
  793. });
  794. }
  795.  
  796. Array.prototype.forEach.call(document.querySelectorAll(".comment-form-textarea,.js-comment-field"), function(commentForm) {
  797. var gollumEditor;
  798. if (commentForm.classList.contains("GithubCommentEnhancer")) {
  799. gollumEditor = commentForm.previousSibling;
  800. } else {
  801. commentForm.classList.add("GithubCommentEnhancer");
  802.  
  803. if (isWiki()) {
  804. gollumEditor = document.getElementById("gollum-editor-function-bar");
  805.  
  806. var helpButton = document.createElement("div");
  807. helpButton.classList.add("button-group", "btn-group");
  808. helpButton.appendChild(document.getElementById("function-help"));
  809.  
  810. var tempLeft = document.createElement("div");
  811. tempLeft.innerHTML = toolBarLeftHTML;
  812. gollumEditor.replaceChild(tempLeft.querySelector("#gollum-editor-function-buttons"), document.getElementById("gollum-editor-function-buttons"));
  813.  
  814. var tempRight = document.createElement("div");
  815. tempRight.innerHTML = toolBarRightHTML;
  816. tempRight.firstElementChild.appendChild(document.createTextNode(" ")); // extra space;
  817. tempRight.firstElementChild.appendChild(helpButton); // restore the help button;
  818. gollumEditor.appendChild(tempRight);
  819.  
  820. tempLeft = tempRight = null;
  821. } else {
  822. gollumEditor = document.createElement("div");
  823. gollumEditor.innerHTML = toolBarLeftHTML + toolBarRightHTML;
  824. gollumEditor.id = "gollum-editor-function-bar";
  825. gollumEditor.style.height = "26px";
  826. gollumEditor.style.margin = "10px 0";
  827. gollumEditor.classList.add("active");
  828. commentForm.parentNode.insertBefore(gollumEditor, commentForm);
  829. }
  830.  
  831. // Execute next block only when suggester is available;
  832. if (commentForm.parentNode.parentNode.querySelector(".suggester-container")) {
  833. fixSuggesterMenu(commentForm);
  834.  
  835. addSuggestions(commentForm);
  836. } else {
  837. Array.prototype.forEach.call(gollumEditor.parentNode.querySelectorAll(".suggester-function"), function(button) {
  838. button.style.display = "none";
  839. });
  840. }
  841.  
  842. addCodeSyntax(commentForm);
  843.  
  844. addSponsorLink(commentForm);
  845. }
  846.  
  847. Array.prototype.forEach.call(gollumEditor.parentNode.querySelectorAll(".function-button"), function(button) {
  848. button.commentForm = commentForm; // remove event listener doesn't accept `bind`;
  849. button.addEventListener("click", buttonEvent, false);
  850. unsafeWindow.$(button).on("navigation:keydown", function(e) {
  851. if (e.hotkey === "enter") {
  852. buttonEvent.call(this, e);
  853. }
  854. });
  855. });
  856.  
  857. commentForm.addEventListener('keydown', commentFormKeyEvent.bind(this, commentForm));
  858. });
  859. }
  860.  
  861. function overrideGollumDialog() {
  862. if (unsafeWindow.$.GollumDialog === undefined) {
  863. (function(e) {
  864. var t = {
  865. markupCreated: !1,
  866. markup: "",
  867. attachEvents: function(o) {
  868. e("#gollum-dialog-action-ok").click(function(e) {
  869. t.eventOK(e, o)
  870. }),
  871. e("#gollum-dialog-action-cancel").click(t.eventCancel),
  872. e('#gollum-dialog-dialog input[type="text"]').keydown(function(e) {
  873. 13 == e.keyCode && t.eventOK(e, o)
  874. })
  875. },
  876. detachEvents: function() {
  877. e("#gollum-dialog-action-ok").unbind("click"),
  878. e("#gollum-dialog-action-cancel").unbind("click")
  879. },
  880. createFieldMarkup: function(e) {
  881. for (var o = "<fieldset>", n = 0; n < e.length; n++)
  882. if ("object" == typeof e[n]) {
  883. switch (o += '<div class="field">',
  884. e[n].type) {
  885. case "text":
  886. o += t.createFieldText(e[n])
  887. }
  888. o += "</div>"
  889. }
  890. return o += "</fieldset>"
  891. },
  892. createFieldText: function(e) {
  893. var t = "";
  894. return e.name && (t += "<label",
  895. e.id && (t += ' for="' + e.name + '"'),
  896. t += ">" + e.name + "</label>"),
  897. t += '<input type="text"',
  898. e.id && (t += ' name="' + e.id + '"',
  899. "code" == e.type && (t += ' class="code"'),
  900. e.value && (t += ' value="' + e.value + '"'),
  901. t += ' id="gollum-dialog-dialog-generated-field-' + e.id + '">'),
  902. t
  903. },
  904. createMarkup: function(o, n) {
  905. return t.markupCreated = !0,
  906. e.facebox ? '<div id="gollum-dialog-dialog"><div id="gollum-dialog-dialog-title"><h4>' + o + '</h4></div><div id="gollum-dialog-dialog-body">' + n + '</div><div id="gollum-dialog-dialog-buttons"><a href="#" title="Cancel" id="gollum-dialog-action-cancel" class="gollum-minibutton">Cancel</a><a href="#" title="OK" id="gollum-dialog-action-ok" class="gollum-minibutton">OK</a></div></div>' : '<div id="gollum-dialog-dialog"><div id="gollum-dialog-dialog-inner"><div id="gollum-dialog-dialog-bg"><div id="gollum-dialog-dialog-title"><h4>' + o + '</h4></div><div id="gollum-dialog-dialog-body">' + n + '</div><div id="gollum-dialog-dialog-buttons"><a href="#" title="Cancel" id="gollum-dialog-action-cancel" class="minibutton">Cancel</a><a href="#" title="OK" id="gollum-dialog-action-ok" class="minibutton">OK</a></div></div></div></div>'
  907. },
  908. eventCancel: function(e) {
  909. e.preventDefault(),
  910. t.hide()
  911. },
  912. eventOK: function(o, n) {
  913. o.preventDefault();
  914. var a = [];
  915. e("#gollum-dialog-dialog-body input").each(function() {
  916. a[e(this).attr("name")] = e(this).val()
  917. }),
  918. n && "function" == typeof n && n(a),
  919. t.hide()
  920. },
  921. hide: function() {
  922. e.facebox ? (t.markupCreated = !1,
  923. e(document).trigger("close.facebox"),
  924. t.detachEvents()) : e.browser.msie ? (e("#gollum-dialog-dialog").hide().removeClass("active"),
  925. e("select").css("visibility", "visible")) : e("#gollum-dialog-dialog").animate({
  926. opacity: 0
  927. }, {
  928. duration: 200,
  929. complete: function() {
  930. e("#gollum-dialog-dialog").removeClass("active")
  931. }
  932. })
  933. },
  934. init: function(o) {
  935. var n = "",
  936. a = "";
  937. o && "object" == typeof o && (o.body && "string" == typeof o.body && (a = "<p>" + o.body + "</p>"),
  938. o.fields && "object" == typeof o.fields && (a += t.createFieldMarkup(o.fields)),
  939. o.title && "string" == typeof o.title && (n = o.title),
  940. t.markupCreated && (e.facebox ? e(document).trigger("close.facebox") : e("#gollum-dialog-dialog").remove()),
  941. t.markup = t.createMarkup(n, a),
  942. e.facebox ? e(document).bind("reveal.facebox", function() {
  943. o.OK && "function" == typeof o.OK && (t.attachEvents(o.OK),
  944. e(e('#facebox input[type="text"]').get(0)).focus())
  945. }) : (e("body").append(t.markup),
  946. o.OK && "function" == typeof o.OK && t.attachEvents(o.OK)),
  947. t.show())
  948. },
  949. show: function() {
  950. t.markupCreated && (e.facebox ? e.facebox(t.markup) : e.browser.msie ? (e("#gollum-dialog.dialog").addClass("active"),
  951. t.position(),
  952. e("select").css("visibility", "hidden")) : (e("#gollum-dialog.dialog").css("display", "none"),
  953. e("#gollum-dialog-dialog").animate({
  954. opacity: 0
  955. }, {
  956. duration: 0,
  957. complete: function() {
  958. e("#gollum-dialog-dialog").css("display", "block"),
  959. t.position(),
  960. e("#gollum-dialog-dialog").animate({
  961. opacity: 1
  962. }, {
  963. duration: 500
  964. })
  965. }
  966. })))
  967. },
  968. position: function() {
  969. var t = e("#gollum-dialog-dialog-inner").height();
  970. e("#gollum-dialog-dialog-inner").css("height", t + "px").css("margin-top", -1 * parseInt(t / 2))
  971. }
  972. };
  973. e.facebox && e(document).bind("reveal.facebox", function() {
  974. e("#facebox img.close_image").remove()
  975. }),
  976. e.GollumDialog = t
  977. })(unsafeWindow.$)
  978. } else {
  979. unsafeWindow.$.GollumEditor.Dialog.createFieldText = unsafeWindow.$.GollumDialog.createFieldText = function(e) {
  980. var t = "";
  981. return e.name && (t += "<label",
  982. e.id && (t += ' for="' + e.name + '"'),
  983. t += ">" + e.name + "</label>"),
  984. t += '<input type="text"',
  985. e.value && (t += ' value="' + e.value + '"'),
  986. e.id && (t += ' name="' + e.id + '"',
  987. "code" == e.type && (t += ' class="code"'),
  988. t += ' id="gollum-dialog-dialog-generated-field-' + e.id + '">'),
  989. t
  990. };
  991. }
  992. }
  993.  
  994. /*
  995. * to-markdown - an HTML to Markdown converter
  996. * Copyright 2011, Dom Christie
  997. * Licenced under the MIT licence
  998. * Source: https://github.com/domchristie/to-markdown
  999. *
  1000. * Code is altered:
  1001. * - Added task list support: https://github.com/domchristie/to-markdown/pull/62
  1002. * - He dependecy is removed
  1003. */
  1004. var toMarkdown = function(string) {
  1005.  
  1006. var ELEMENTS = [{
  1007. patterns: 'p',
  1008. replacement: function(str, attrs, innerHTML) {
  1009. return innerHTML ? '\n\n' + innerHTML + '\n' : '';
  1010. }
  1011. }, {
  1012. patterns: 'br',
  1013. type: 'void',
  1014. replacement: ' \n'
  1015. }, {
  1016. patterns: 'h([1-6])',
  1017. replacement: function(str, hLevel, attrs, innerHTML) {
  1018. var hPrefix = '';
  1019. for (var i = 0; i < hLevel; i++) {
  1020. hPrefix += '#';
  1021. }
  1022. return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
  1023. }
  1024. }, {
  1025. patterns: 'hr',
  1026. type: 'void',
  1027. replacement: '\n\n* * *\n'
  1028. }, {
  1029. patterns: 'a',
  1030. replacement: function(str, attrs, innerHTML) {
  1031. var href = attrs.match(attrRegExp('href')),
  1032. title = attrs.match(attrRegExp('title'));
  1033. return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
  1034. }
  1035. }, {
  1036. patterns: ['b', 'strong'],
  1037. replacement: function(str, attrs, innerHTML) {
  1038. return innerHTML ? '**' + innerHTML + '**' : '';
  1039. }
  1040. }, {
  1041. patterns: ['i', 'em'],
  1042. replacement: function(str, attrs, innerHTML) {
  1043. return innerHTML ? '_' + innerHTML + '_' : '';
  1044. }
  1045. }, {
  1046. patterns: 'code',
  1047. replacement: function(str, attrs, innerHTML) {
  1048. return innerHTML ? '`' + innerHTML + '`' : '';
  1049. }
  1050. }, {
  1051. patterns: 'img',
  1052. type: 'void',
  1053. replacement: function(str, attrs, innerHTML) {
  1054. var src = attrs.match(attrRegExp('src')),
  1055. alt = attrs.match(attrRegExp('alt')),
  1056. title = attrs.match(attrRegExp('title'));
  1057. return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
  1058. }
  1059. }];
  1060.  
  1061. for (var i = 0, len = ELEMENTS.length; i < len; i++) {
  1062. if (typeof ELEMENTS[i].patterns === 'string') {
  1063. string = replaceEls(string, {
  1064. tag: ELEMENTS[i].patterns,
  1065. replacement: ELEMENTS[i].replacement,
  1066. type: ELEMENTS[i].type
  1067. });
  1068. } else {
  1069. for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
  1070. string = replaceEls(string, {
  1071. tag: ELEMENTS[i].patterns[j],
  1072. replacement: ELEMENTS[i].replacement,
  1073. type: ELEMENTS[i].type
  1074. });
  1075. }
  1076. }
  1077. }
  1078.  
  1079. function replaceEls(html, elProperties) {
  1080. var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
  1081. regex = new RegExp(pattern, 'gi'),
  1082. markdown = '';
  1083. if (typeof elProperties.replacement === 'string') {
  1084. markdown = html.replace(regex, elProperties.replacement);
  1085. } else {
  1086. markdown = html.replace(regex, function(str, p1, p2, p3) {
  1087. return elProperties.replacement.call(this, str, p1, p2, p3);
  1088. });
  1089. }
  1090. return markdown;
  1091. }
  1092.  
  1093. function attrRegExp(attr) {
  1094. return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
  1095. }
  1096.  
  1097. // Pre code blocks
  1098.  
  1099. string = string.replace(/<pre\b[^>]*>`([\s\S]*?)`<\/pre>/gi, function(str, innerHTML) {
  1100. var text = innerHTML;
  1101. text = text.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense)
  1102. text = text.replace(/\n/g, '\n ');
  1103. return '\n\n ' + text + '\n';
  1104. });
  1105.  
  1106. // Lists
  1107.  
  1108. // Escape numbers that could trigger an ol
  1109. // If there are more than three spaces before the code, it would be in a pre tag
  1110. // Make sure we are escaping the period not matching any character
  1111. string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');
  1112.  
  1113. // Converts lists that have no child lists (of same type) first, then works its way up
  1114. var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
  1115. while (string.match(noChildrenRegex)) {
  1116. string = string.replace(noChildrenRegex, function(str) {
  1117. return replaceLists(str);
  1118. });
  1119. }
  1120.  
  1121. function replaceLists(html) {
  1122.  
  1123. html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) {
  1124. var lis = innerHTML.split('</li>');
  1125. lis.splice(lis.length - 1, 1);
  1126.  
  1127. for (i = 0, len = lis.length; i < len; i++) {
  1128. if (lis[i]) {
  1129. var prefix = (listType === 'ol') ? (i + 1) + ". " : "* ";
  1130. lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) {
  1131. innerHTML = innerHTML.replace(/\s*<input[^>]*?(checked[^>]*)?type=['"]?checkbox['"]?[^>]>/, function(inputStr, checked) {
  1132. return checked ? '[X]' : '[ ]';
  1133. });
  1134. innerHTML = innerHTML.replace(/^\s+/, '');
  1135. innerHTML = innerHTML.replace(/\n\n/g, '\n\n ');
  1136. // indent nested lists
  1137. innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 ');
  1138. return prefix + innerHTML;
  1139. });
  1140. }
  1141. lis[i] = lis[i].replace(/(.) +$/m, '$1');
  1142. }
  1143. return lis.join('\n');
  1144. });
  1145.  
  1146. return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
  1147. }
  1148.  
  1149. // Blockquotes
  1150. var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
  1151. while (string.match(deepest)) {
  1152. string = string.replace(deepest, function(str) {
  1153. return replaceBlockquotes(str);
  1154. });
  1155. }
  1156.  
  1157. function replaceBlockquotes(html) {
  1158. html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) {
  1159. inner = inner.replace(/^\s+|\s+$/g, '');
  1160. inner = cleanUp(inner);
  1161. inner = inner.replace(/^/gm, '> ');
  1162. inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
  1163. return inner;
  1164. });
  1165. return html;
  1166. }
  1167.  
  1168. function cleanUp(string) {
  1169. string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
  1170. string = string.replace(/\n\s+\n/g, '\n\n');
  1171. string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
  1172. return string;
  1173. }
  1174.  
  1175. return cleanUp(string);
  1176. };
  1177.  
  1178. function getCommentTextarea(replyBtn) {
  1179. var newComment = replyBtn;
  1180. while (newComment && !newComment.classList.contains('js-quote-selection-container')) {
  1181. newComment = newComment.parentNode;
  1182. }
  1183. if (newComment) {
  1184. var lastElementChild = newComment.lastElementChild;
  1185. lastElementChild.classList.add('open');
  1186. newComment = lastElementChild.querySelector(".comment-form-textarea");
  1187. } else {
  1188. newComment = document.querySelector(".timeline-new-comment .comment-form-textarea");
  1189. }
  1190. return newComment;
  1191. }
  1192.  
  1193. function addReplyButtons() {
  1194. Array.prototype.forEach.call(document.querySelectorAll(".comment"), function(comment) {
  1195. var oldReply = comment.querySelector(".GithubCommentEnhancerReply");
  1196. if (oldReply) {
  1197. oldReply.parentNode.removeChild(oldReply);
  1198. }
  1199.  
  1200. var header = comment.querySelector(".timeline-comment-header"),
  1201. actions = comment.querySelector(".timeline-comment-actions");
  1202.  
  1203. if (!header) {
  1204. return;
  1205. }
  1206. if (!actions) {
  1207. actions = document.createElement("div");
  1208. actions.classList.add("timeline-comment-actions");
  1209. header.insertBefore(actions, header.firstElementChild);
  1210. }
  1211.  
  1212. var reply = document.createElement("a");
  1213. reply.setAttribute("href", "#");
  1214. reply.setAttribute("aria-label", "Reply to this comment");
  1215. reply.classList.add("GithubCommentEnhancerReply", "timeline-comment-action", "tooltipped", "tooltipped-ne");
  1216. reply.addEventListener("click", function(e) {
  1217. e.preventDefault();
  1218.  
  1219. var newComment = getCommentTextarea(this);
  1220.  
  1221. var timestamp = comment.querySelector(".timestamp");
  1222.  
  1223. var commentText = comment.querySelector(".comment-form-textarea");
  1224. if (commentText) {
  1225. commentText = commentText.value;
  1226. } else {
  1227. commentText = toMarkdown(comment.querySelector(".comment-body").innerHTML);
  1228. }
  1229. commentText = commentText.trim().split("\n").map(function(line) {
  1230. return "> " + line;
  1231. }).join("\n");
  1232.  
  1233. var text = newComment.value.length > 0 ? "\n" : "";
  1234. text += String.format('[**@{0}**]({1}/{0}) commented on [{2}]({3} "{4} - Replied by Github Comment Enhancer"):\n{5}\n\n',
  1235. comment.querySelector(".author").textContent,
  1236. location.origin,
  1237. timestamp.firstElementChild.getAttribute("title"),
  1238. timestamp.href,
  1239. timestamp.firstElementChild.getAttribute("datetime"),
  1240. commentText);
  1241.  
  1242. newComment.value += text;
  1243. newComment.setSelectionRange(newComment.value.length, newComment.value.length);
  1244. newComment.focus();
  1245. });
  1246.  
  1247. var replyIcon = document.createElement("span");
  1248. replyIcon.classList.add("octicon", "octicon-mail-reply");
  1249. reply.appendChild(replyIcon);
  1250.  
  1251. actions.appendChild(reply);
  1252. });
  1253. }
  1254.  
  1255. // init;
  1256. function init() {
  1257. addToolbar();
  1258. addReplyButtons();
  1259. }
  1260. overrideGollumDialog();
  1261. init();
  1262.  
  1263. // on pjax;
  1264. unsafeWindow.$(document).on("pjax:end", init); // `pjax:end` also runs on history back;
  1265.  
  1266. // For inline comments on commits;
  1267. var files = document.querySelectorAll('.diff-table');
  1268. Array.prototype.forEach.call(files, function(file) {
  1269. file = file.firstElementChild;
  1270. new MutationObserver(function(mutations) {
  1271. mutations.forEach(function(mutation) {
  1272. if (mutation.target === file) {
  1273. addToolbar();
  1274. }
  1275. });
  1276. }).observe(file, {
  1277. childList: true,
  1278. subtree: true
  1279. });
  1280. });
  1281.  
  1282. })(typeof unsafeWindow !== "undefined" ? unsafeWindow : window);

QingJ © 2025

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