GitHub RTL Comment Blocks

A userscript that adds a button to insert RTL text blocks in comments

As of 2016-06-15. See the latest version.

  1. // ==UserScript==
  2. // @name GitHub RTL Comment Blocks
  3. // @version 1.1.0
  4. // @description A userscript that adds a button to insert RTL text blocks in comments
  5. // @license https://creativecommons.org/licenses/by-sa/4.0/
  6. // @namespace http://github.com/Mottie
  7. // @include https://github.com/*
  8. // @run-at document-idle
  9. // @grant GM_addStyle
  10. // @connect github.com
  11. // @author Rob Garrison
  12. // ==/UserScript==
  13. /*jshint unused:true, esnext:true */
  14. /* global GM_addStyle */
  15. (function() {
  16. "use strict";
  17.  
  18. let targets,
  19. busy = false;
  20.  
  21. const icon = `
  22. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 14 14">
  23. <path d="M14 3v8l-4-4m-7 7V6C1 6 0 5 0 3s1-3 3-3h7v2H9v12H7V2H5v12H3z"/>
  24. </svg>`,
  25.  
  26. // maybe using &#x2067; RTL text &#x2066; (isolates) is a better combo?
  27. openRTL = "&rlm;", // https://en.wikipedia.org/wiki/Right-to-left_mark
  28. closeRTL = "&lrm;", // https://en.wikipedia.org/wiki/Left-to-right_mark
  29.  
  30. regexOpen = /\u200f/ig,
  31. regexClose = /\u200e/ig,
  32. regexSplit = /(\u200f|\u200e)/ig;
  33.  
  34. GM_addStyle(`
  35. .ghu-rtl-css { direction:rtl; text-align:right; unicode-bidi:isolate; }
  36. /* delegated binding; ignore clicks on svg & path */
  37. .ghu-rtl > * { pointer-events:none; }
  38. /* override RTL on code blocks */
  39. .js-preview-body pre, .markdown-body pre, .js-preview-body code, .markdown-body code {
  40. direction:ltr;
  41. text-align:left;
  42. unicode-bidi:normal;
  43. }
  44. `);
  45.  
  46. // Add monospace font toggle
  47. function addRtlButton() {
  48. busy = true;
  49. let el, button,
  50. toolbars = $$(".toolbar-commenting"),
  51. indx = toolbars.length;
  52. if (indx) {
  53. button = document.createElement("button");
  54. button.type = "button";
  55. button.className = "ghu-rtl toolbar-item tooltipped tooltipped-n";
  56. button.setAttribute("aria-label", "RTL");
  57. button.setAttribute("tabindex", "-1");
  58. button.innerHTML = icon;
  59. while (indx--) {
  60. el = toolbars[indx];
  61. if (!$(".ghu-rtl", el)) {
  62. el.insertBefore(button.cloneNode(true), el.childNodes[0]);
  63. }
  64. }
  65. }
  66. checkRTL();
  67. busy = false;
  68. }
  69.  
  70. function checkContent(el) {
  71. // check the contents, and wrap in either a span or div
  72. let indx, // useDiv,
  73. html = el.innerHTML,
  74. parts = html.split(regexSplit),
  75. len = parts.length;
  76. for (indx = 0; indx < len; indx++) {
  77. if (regexOpen.test(parts[indx])) {
  78. // check if the content contains HTML
  79. // useDiv = regexTestHTML.test(parts[indx + 1]);
  80. // parts[indx] = (useDiv ? "<div" : "<span") + " class='ghu-rtl-css'>";
  81. parts[indx] = "<div class='ghu-rtl-css'>";
  82. } else if (regexClose.test(parts[indx])) {
  83. // parts[indx] = useDiv ? "</div>" : "</span>";
  84. parts[indx] = "</div>";
  85. }
  86. }
  87. el.innerHTML = parts.join("");
  88. // remove empty paragraph wrappers (may have previously contained the mark)
  89. return el.innerHTML.replace(/<p><\/p>/g, "");
  90. }
  91.  
  92. function checkRTL() {
  93. let clone,
  94. indx = 0,
  95. div = document.createElement("div"),
  96. containers = $$(".js-preview-body, .markdown-body"),
  97. len = containers.length,
  98. // main loop
  99. loop = function() {
  100. let el, tmp,
  101. max = 0;
  102. while (max < 10 && indx < len) {
  103. if (indx > len) {
  104. return;
  105. }
  106. el = containers[indx];
  107. tmp = el.innerHTML;
  108. if (regexOpen.test(tmp) || regexClose.test(tmp)) {
  109. clone = div.cloneNode();
  110. clone.innerHTML = tmp;
  111. // now we can replace all instances
  112. el.innerHTML = checkContent(clone);
  113. max++;
  114. }
  115. indx++;
  116. }
  117. if (indx < len) {
  118. setTimeout(function() {
  119. loop();
  120. }, 200);
  121. }
  122. };
  123. loop();
  124. }
  125.  
  126. function $(selector, el) {
  127. return (el || document).querySelector(selector);
  128. }
  129. function $$(selector, el) {
  130. return Array.from((el || document).querySelectorAll(selector));
  131. }
  132. function closest(el, selector) {
  133. while (el && el.nodeName !== "BODY" && !el.matches(selector)) {
  134. el = el.parentNode;
  135. }
  136. return el && el.matches(selector) ? el : [];
  137. }
  138.  
  139. function addBindings() {
  140. $("body").addEventListener("click", function(event) {
  141. let textarea,
  142. target = event.target;
  143. if (target && target.classList.contains("ghu-rtl")) {
  144. textarea = closest(target, ".previewable-comment-form");
  145. textarea = $(".comment-form-textarea", textarea);
  146. textarea.focus();
  147. // add extra white space around the tags
  148. surroundSelectedText(textarea, ' ' + openRTL + ' ', ' ' + closeRTL + ' ');
  149. return false;
  150. }
  151. });
  152. }
  153.  
  154. targets = $$("#js-repo-pjax-container, #js-pjax-container, .js-preview-body");
  155.  
  156. Array.prototype.forEach.call(targets, function(target) {
  157. new MutationObserver(function(mutations) {
  158. mutations.forEach(function(mutation) {
  159. // preform checks before adding code wrap to minimize function calls
  160. if (!busy && mutation.target === target) {
  161. addRtlButton();
  162. }
  163. });
  164. }).observe(target, {
  165. childList: true,
  166. subtree: true
  167. });
  168. });
  169.  
  170. addBindings();
  171. addRtlButton();
  172.  
  173. /* HEAVILY MODIFIED from https://github.com/timdown/rangyinputs
  174. code was unwrapped & unneeded code was removed
  175. */
  176. /**
  177. * @license Rangy Inputs, a jQuery plug-in for selection and caret manipulation within textareas and text inputs.
  178. *
  179. * https://github.com/timdown/rangyinputs
  180. *
  181. * For range and selection features for contenteditable, see Rangy.
  182. * http://code.google.com/p/rangy/
  183. *
  184. * Depends on jQuery 1.0 or later.
  185. *
  186. * Copyright 2014, Tim Down
  187. * Licensed under the MIT license.
  188. * Version: 1.2.0
  189. * Build date: 30 November 2014
  190. */
  191. var UNDEF = "undefined";
  192. var getSelection, setSelection, surroundSelectedText;
  193.  
  194. // Trio of isHost* functions taken from Peter Michaux's article:
  195. // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
  196. function isHostMethod(object, property) {
  197. var t = typeof object[property];
  198. return t === "function" || (!!(t == "object" && object[property])) || t == "unknown";
  199. }
  200. function isHostProperty(object, property) {
  201. return typeof(object[property]) != UNDEF;
  202. }
  203. function isHostObject(object, property) {
  204. return !!(typeof(object[property]) == "object" && object[property]);
  205. }
  206. function fail(reason) {
  207. if (window.console && window.console.log) {
  208. window.console.log("RangyInputs not supported in your browser. Reason: " + reason);
  209. }
  210. }
  211.  
  212. function adjustOffsets(el, start, end) {
  213. if (start < 0) {
  214. start += el.value.length;
  215. }
  216. if (typeof end == UNDEF) {
  217. end = start;
  218. }
  219. if (end < 0) {
  220. end += el.value.length;
  221. }
  222. return { start: start, end: end };
  223. }
  224.  
  225. function makeSelection(el, start, end) {
  226. return {
  227. start: start,
  228. end: end,
  229. length: end - start,
  230. text: el.value.slice(start, end)
  231. };
  232. }
  233.  
  234. function getBody() {
  235. return isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0];
  236. }
  237.  
  238. var testTextArea = document.createElement("textarea");
  239. getBody().appendChild(testTextArea);
  240.  
  241. if (isHostProperty(testTextArea, "selectionStart") && isHostProperty(testTextArea, "selectionEnd")) {
  242. getSelection = function(el) {
  243. var start = el.selectionStart, end = el.selectionEnd;
  244. return makeSelection(el, start, end);
  245. };
  246.  
  247. setSelection = function(el, startOffset, endOffset) {
  248. var offsets = adjustOffsets(el, startOffset, endOffset);
  249. el.selectionStart = offsets.start;
  250. el.selectionEnd = offsets.end;
  251. };
  252. } else if (isHostMethod(testTextArea, "createTextRange") && isHostObject(document, "selection") &&
  253. isHostMethod(document.selection, "createRange")) {
  254.  
  255. getSelection = function(el) {
  256. var start = 0, end = 0, normalizedValue, textInputRange, len, endRange;
  257. var range = document.selection.createRange();
  258.  
  259. if (range && range.parentElement() == el) {
  260. len = el.value.length;
  261.  
  262. normalizedValue = el.value.replace(/\r\n/g, "\n");
  263. textInputRange = el.createTextRange();
  264. textInputRange.moveToBookmark(range.getBookmark());
  265. endRange = el.createTextRange();
  266. endRange.collapse(false);
  267. if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
  268. start = end = len;
  269. } else {
  270. start = -textInputRange.moveStart("character", -len);
  271. start += normalizedValue.slice(0, start).split("\n").length - 1;
  272. if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
  273. end = len;
  274. } else {
  275. end = -textInputRange.moveEnd("character", -len);
  276. end += normalizedValue.slice(0, end).split("\n").length - 1;
  277. }
  278. }
  279. }
  280.  
  281. return makeSelection(el, start, end);
  282. };
  283.  
  284. // Moving across a line break only counts as moving one character in a TextRange, whereas a line break in
  285. // the textarea value is two characters. This function corrects for that by converting a text offset into a
  286. // range character offset by subtracting one character for every line break in the textarea prior to the
  287. // offset
  288. var offsetToRangeCharacterMove = function(el, offset) {
  289. return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
  290. };
  291.  
  292. setSelection = function(el, startOffset, endOffset) {
  293. var offsets = adjustOffsets(el, startOffset, endOffset);
  294. var range = el.createTextRange();
  295. var startCharMove = offsetToRangeCharacterMove(el, offsets.start);
  296. range.collapse(true);
  297. if (offsets.start == offsets.end) {
  298. range.move("character", startCharMove);
  299. } else {
  300. range.moveEnd("character", offsetToRangeCharacterMove(el, offsets.end));
  301. range.moveStart("character", startCharMove);
  302. }
  303. range.select();
  304. };
  305. } else {
  306. getBody().removeChild(testTextArea);
  307. fail("No means of finding text input caret position");
  308. return;
  309. }
  310. // Clean up
  311. getBody().removeChild(testTextArea);
  312.  
  313. function getValueAfterPaste(el, text) {
  314. var val = el.value, sel = getSelection(el), selStart = sel.start;
  315. return {
  316. value: val.slice(0, selStart) + text + val.slice(sel.end),
  317. index: selStart,
  318. replaced: sel.text
  319. };
  320. }
  321.  
  322. function pasteTextWithCommand(el, text) {
  323. el.focus();
  324. var sel = getSelection(el);
  325.  
  326. // Hack to work around incorrect delete command when deleting the last word on a line
  327. setSelection(el, sel.start, sel.end);
  328. if (text === "") {
  329. document.execCommand("delete", false, null);
  330. } else {
  331. document.execCommand("insertText", false, text);
  332. }
  333.  
  334. return {
  335. replaced: sel.text,
  336. index: sel.start
  337. };
  338. }
  339.  
  340. function pasteTextWithValueChange(el, text) {
  341. el.focus();
  342. var valueAfterPaste = getValueAfterPaste(el, text);
  343. el.value = valueAfterPaste.value;
  344. return valueAfterPaste;
  345. }
  346.  
  347. var pasteText = function(el, text) {
  348. var valueAfterPaste = getValueAfterPaste(el, text);
  349. try {
  350. var pasteInfo = pasteTextWithCommand(el, text);
  351. if (el.value == valueAfterPaste.value) {
  352. pasteText = pasteTextWithCommand;
  353. return pasteInfo;
  354. }
  355. } catch (ex) {
  356. // Do nothing and fall back to changing the value manually
  357. }
  358. pasteText = pasteTextWithValueChange;
  359. el.value = valueAfterPaste.value;
  360. return valueAfterPaste;
  361. };
  362.  
  363. var updateSelectionAfterInsert = function(el, startIndex, text, selectionBehaviour) {
  364. var endIndex = startIndex + text.length;
  365.  
  366. selectionBehaviour = (typeof selectionBehaviour == "string") ?
  367. selectionBehaviour.toLowerCase() : "";
  368.  
  369. if ((selectionBehaviour == "collapsetoend" || selectionBehaviour == "select") && /[\r\n]/.test(text)) {
  370. // Find the length of the actual text inserted, which could vary
  371. // depending on how the browser deals with line breaks
  372. var normalizedText = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  373. endIndex = startIndex + normalizedText.length;
  374. var firstLineBreakIndex = startIndex + normalizedText.indexOf("\n");
  375.  
  376. if (el.value.slice(firstLineBreakIndex, firstLineBreakIndex + 2) == "\r\n") {
  377. // Browser uses \r\n, so we need to account for extra \r characters
  378. endIndex += normalizedText.match(/\n/g).length;
  379. }
  380. }
  381.  
  382. switch (selectionBehaviour) {
  383. case "collapsetostart":
  384. setSelection(el, startIndex, startIndex);
  385. break;
  386. case "collapsetoend":
  387. setSelection(el, endIndex, endIndex);
  388. break;
  389. case "select":
  390. setSelection(el, startIndex, endIndex);
  391. break;
  392. }
  393. };
  394.  
  395. surroundSelectedText = function(el, before, after, selectionBehaviour) {
  396. if (typeof after == UNDEF) {
  397. after = before;
  398. }
  399. var sel = getSelection(el);
  400. var pasteInfo = pasteText(el, before + sel.text + after);
  401. updateSelectionAfterInsert(el, pasteInfo.index + before.length, sel.text, selectionBehaviour || "select");
  402. };
  403.  
  404. })();