AO3: Comment Formatting and Preview

Adds buttons to insert HTML formatting, and shows a live preview box of what the comment will look like

当前为 2024-01-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AO3: Comment Formatting and Preview
  3. // @namespace https://greasyfork.org/en/users/906106-escctrl
  4. // @version 1.0
  5. // @description Adds buttons to insert HTML formatting, and shows a live preview box of what the comment will look like
  6. // @author escctrl
  7. // @license MIT
  8. // @match *://*.archiveofourown.org/tags/*/comments*
  9. // @match *://*.archiveofourown.org/users/*/inbox*
  10. // @match *://*.archiveofourown.org/works/*
  11. // @match *://*.archiveofourown.org/comments/*
  12. // @match *://*.archiveofourown.org/comments?*
  13. // @grant none
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js
  15. // @require https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js
  16. // @require https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js
  17. // ==/UserScript==
  18.  
  19. (function($) {
  20. 'use strict';
  21.  
  22. /*********************************************************
  23. GUI CONFIGURATION
  24. *********************************************************/
  25.  
  26. // load storage on page startup
  27. var standardmap = new Map(JSON.parse(localStorage.getItem('cmtfmtstandard'))); // only a key: true/false list
  28. var custommap = new Map(JSON.parse(localStorage.getItem('cmtfmtcustom'))); // all content we need from user to display & insert what they want
  29.  
  30. // if the background is dark, use the dark UI theme to match
  31. let dialogtheme = lightOrDark($('body').css('background-color')) == "dark" ? "ui-darkness" : "base";
  32.  
  33. // the config dialog container
  34. let cfg = document.createElement('div');
  35. cfg.id = 'cmtFmtDialog';
  36.  
  37. // adding the jQuery stylesheet to style the dialog, and fixing the interferance of AO3's styling
  38. $("head").append(`<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/${dialogtheme}/jquery-ui.css">`)
  39. .prepend(`<script src="https://use.fontawesome.com/ed555db3cc.js" />`)
  40. .append(`<style tyle="text/css">#${cfg.id}, .ui-dialog .ui-dialog-buttonpane button {font-size: revert; line-height: 1.286;}
  41. #${cfg.id} form {box-shadow: revert; cursor:auto;}
  42. #${cfg.id} #custombutton a {cursor:pointer;}
  43. #${cfg.id} legend {font-size: inherit; height: auto; width: auto; opacity: inherit;}
  44. #${cfg.id} fieldset {background: revert; box-shadow: revert;}
  45. #${cfg.id} input[type='text'] { position: relative; top: 1px; padding: .4em; width: 3em; }
  46. #${cfg.id} ul { padding-left: 2em; }
  47. #${cfg.id} ul li { list-style: circle; }
  48. #${cfg.id} #stdbutton label { font-family: FontAwesome, sans-serif; }
  49. #${cfg.id} #custombutton div button { width: 0.5em; }
  50. #${cfg.id} #custombutton div input:nth-of-type(1) { width: 2em; }
  51. #${cfg.id} #custombutton div input:nth-of-type(2) { width: 6em; }
  52. #${cfg.id} #custombutton div input:nth-of-type(3) { width: 10em; }
  53. #${cfg.id} #custombutton div input:nth-of-type(4) { width: 10em; }
  54. </style>`);
  55.  
  56. // the available standard buttons, display & insert stuff
  57. let config_std = new Map([
  58. ["bold", { icon: "&#xf032;", text: "Bold", ins_pre: "<b>", ins_app: "</b>" }],
  59. ["italic", { icon: "&#xf033;", text: "Italic", ins_pre: "<em>", ins_app: "</em>" }],
  60. ["underline", { icon: "&#xf0cd;", text: "Underline", ins_pre: "<u>", ins_app: "</u>" }],
  61. ["strike", { icon: "&#xf0cc;", text: "Strikethrough", ins_pre: "<s>", ins_app: "</s>" }],
  62. ["link", { icon: "&#xf0c1;", text: "Link", ins_pre: "<a href=\"\">", ins_app: "</a>" }],
  63. ["image", { icon: "&#xf03e;", text: "Image", ins_pre: "<img src=\"", ins_app: "\" />" }],
  64. ["quote", { icon: "&#xf10d;", text: "Quote", ins_pre: "<blockquote>", ins_app: "</blockquote>" }],
  65. ["paragraph", { icon: "&#xf1dd;", text: "Paragraph", ins_pre: "<p>", ins_app: "</p>" }],
  66. ["listnum", { icon: "&#xf0cb;", text: "Numbered List", ins_pre: "<ol><li>", ins_app: "</li></ol>" }],
  67. ["listbull", { icon: "&#xf0ca;", text: "Bullet List", ins_pre: "<ul><li>", ins_app: "</li></ul>" }],
  68. ["listitem", { icon: "&#xf192;", text: "List Item", ins_pre: "<li>", ins_app: "</li>" }],
  69. ]);
  70.  
  71. let standardbuttons = '';
  72. config_std.forEach((val, key) => {
  73. standardbuttons += `<label for="${key}" title="${val.text}">${val.icon}</label><input type="checkbox" name="${key}" id="${key}" ${(standardmap.get(key)==="true" || standardmap.size == 0) ? 'checked="checked"' : ""}>`;
  74. });
  75.  
  76. let newcustombutton = `<div><button class="remove">-</button><input type="text" name="icon" value="Icon"><input type="text" name="text" value="Title">
  77. <input type="text" name="ins_pre" value="Insert Before"><input type="text" name="ins_app" value="Insert After"></div>`;
  78.  
  79. // turn custom buttons into Map items
  80. /*
  81. ["custom1", { icon: "&#xf1ab;", text: "Translation", ins_pre: "Translation: ", ins_app: "" }]
  82. */
  83. let config_custom = new Map();
  84. custommap.forEach((val, key) => {
  85. val = JSON.parse(val); // turn the string into an array of 4x2 each
  86. let newval = {}; // turn the array into an object
  87. val.forEach((v) => {
  88. newval[v[0]] = v[1];
  89. });
  90. config_custom.set(key, newval);
  91. });
  92.  
  93. let custombuttons = '';
  94. config_custom.forEach((val, key) => {
  95. custombuttons += `<div><button class="remove">-</button><input type="text" name="icon" value="${val.icon}"><input type="text" name="text" value="${val.text}">
  96. <input type="text" name="ins_pre" value="${val.ins_pre}"><input type="text" name="ins_app" value="${val.ins_app}"></div>`;
  97. });
  98.  
  99. $(cfg).html(`
  100. <form>
  101. <fieldset id='stdbutton'>
  102. <legend>Standard text formatting</legend>
  103. <p>Select the buttons you'd like to see as options on the button bar.</p>
  104. ${standardbuttons}
  105. </fieldset>
  106. <fieldset id='custombutton'>
  107. <legend>Custom HTML or text</legend>
  108. <p>Define custom buttons, which will insert HTML and/or text.</p>
  109. <ul><li>In the first field, choose <a href="https://fontawesome.com/v4/icons/">the Icon</a> you want on the button.<br />
  110. Copy its 4-letter Unicode (for example "f004" for the heart) into this field.</li>
  111. <li>If you leave the Icon field empty, the Title from the second field is shown on the button instead. The Title also appears as mouseover text.</li>
  112. <li>Put the text you want inserted around the cursor position into the Insert Before and Insert After fields.</li></ul>
  113. ${custombuttons}
  114. <div><button class="add">+</button></div>
  115. </fieldset>
  116. <p>Any changes only apply after reloading the page.</p>
  117. </form>
  118. `);
  119.  
  120. // attach it to the DOM so that selections work (but only if #main exists, else it might be a Retry Later error page)
  121. if ($("#main").length == 1) $("body").append(cfg);
  122.  
  123. // turn checkboxes and radiobuttons into pretty buttons
  124. $( "#cmtFmtDialog input[type='checkbox'], #cmtFmtDialog input[type='radio']" ).checkboxradio({
  125. icon: false
  126. });
  127.  
  128. // optimizing the size of the GUI in case it's a mobile device
  129. let dialogwidth = parseInt($("body").css("width")); // parseInt ignores letters (px)
  130. dialogwidth = dialogwidth > 550 ? 550 : dialogwidth * 0.9;
  131.  
  132. // initialize the dialog (but don't open it)
  133. $( "#cmtFmtDialog" ).dialog({
  134. appendTo: "#main",
  135. modal: true,
  136. title: 'Comment Formatting Buttons',
  137. draggable: true,
  138. resizable: false,
  139. autoOpen: false,
  140. width: dialogwidth,
  141. position: {my:"center", at: "center top"},
  142. buttons: {
  143. Reset: deleteConfig,
  144. Save: storeConfig,
  145. Cancel: function() {
  146. $( "#cmtFmtDialog" ).dialog( "close" );
  147. }
  148. }
  149. });
  150.  
  151. // event triggers if form is submitted with the <enter> key
  152. $( "#cmtFmtDialog form" ).on("submit", (e)=>{
  153. e.preventDefault();
  154. storeConfig();
  155. });
  156.  
  157. // putting event triggers on buttons that will delete custom rows
  158. function evRemoveRow(el) {
  159. $(el).on("click", (e) => {
  160. e.cancelBubble = true;
  161. e.preventDefault();
  162. $(e.target).parent().remove(); // delete whole div
  163. });
  164. }
  165. // run it immediately on the stored custom buttons
  166. evRemoveRow($( "#cmtFmtDialog button.remove" ));
  167.  
  168. // putting event trigger on button that will add blank custom rows
  169. $( "#cmtFmtDialog button.add" ).on("click", (e) => {
  170. e.cancelBubble = true;
  171. e.preventDefault();
  172. // add a new blank row and attach the remove event again
  173. $(e.target).parent().before( $(newcustombutton).clone() );
  174. evRemoveRow($( "#cmtFmtDialog button.remove:last-of-type" ));
  175. });
  176.  
  177. function deleteConfig() {
  178. // deselects all buttons, empties all fields in the form
  179. $('#cmtFmtDialog form').trigger("reset");
  180. $('#cmtFmtDialog button.remove').trigger("click");
  181.  
  182. // deletes the localStorage
  183. localStorage.removeItem('cmtfmtstandard');
  184. localStorage.removeItem('cmtfmtcustom');
  185.  
  186. $( "#cmtFmtDialog" ).dialog( "close" );
  187. }
  188.  
  189. function storeConfig() {
  190. // build a Map() for enabled standard buttons => true/false
  191. let storestd = new Map();
  192. $( "#cmtFmtDialog #stdbutton [name]" ).each((i, fmt) => {
  193. storestd.set($(fmt).prop('name'), String($(fmt).prop('checked')));
  194. });
  195. localStorage.setItem('cmtfmtstandard', JSON.stringify(Array.from(storestd.entries())));
  196.  
  197. let storecustom = new Map();
  198. $( "#cmtFmtDialog #custombutton div:has(input)" ).each((i, div) => {
  199. let parts = new Map();
  200. $(div).find('[name]').each((j, fmt) => { parts.set($(fmt).prop('name'), $(fmt).prop('value')); });
  201. storecustom.set('custom'+i, JSON.stringify(Array.from(parts.entries())));
  202. });
  203. localStorage.setItem('cmtfmtcustom', JSON.stringify(Array.from(storecustom.entries())));
  204.  
  205. $( "#cmtFmtDialog" ).dialog( "close" );
  206. }
  207.  
  208. /* CREATING THE LINK TO OPEN THE CONFIGURATION DIALOG */
  209.  
  210. // if no other script has created it yet, write out a "Userscripts" option to the main navigation
  211. if ($('#scriptconfig').length == 0) {
  212. $('#header ul.primary.navigation li.dropdown').last()
  213. .after(`<li class="dropdown" id="scriptconfig">
  214. <a class="dropdown-toggle" href="/" data-toggle="dropdown" data-target="#">Userscripts</a>
  215. <ul class="menu dropdown-menu"></ul>
  216. </li>`);
  217. }
  218. // then add this script's config option to navigation dropdown
  219. $('#scriptconfig .dropdown-menu').append(`<li><a href="javascript:void(0);" id="opencfg_cmtfmt">Comment Formatting Buttons</a></li>`);
  220.  
  221. // on click, open the configuration dialog
  222. $("#opencfg_cmtfmt").on("click", function(e) {
  223. $( "#cmtFmtDialog" ).dialog('open');
  224. });
  225.  
  226. /*********************************************************
  227. COMMENT BAR AND PREVIEW FUNCTIONALITY
  228. *********************************************************/
  229.  
  230. // merge the enabled standard and custom buttons into one list
  231. let config = new Map();
  232. config_std.forEach((val, key) => { if (standardmap.get(key)==="true" || standardmap.size == 0) config.set(key, val); });
  233. config_custom.forEach((val, key) => {
  234. if (val.icon !== "") val.icon = `&#x${val.icon};`; // add what Font Awesome needs to display properly
  235. config.set(key, val);
  236. });
  237.  
  238. $("head").append(`<style type="text/css"> ul.comment-format { font-family: FontAwesome, sans-serif; float: left; }
  239. ul.comment-format a { cursor: default; }
  240. ul.comment-format .fontawe { font-family: FontAwesome, sans-serif; }
  241. div.comment-preview.userstuff { border: 1px inset #f0f0f0; min-height: 1em; padding: 0.2em 1em; line-height: 1.5; } </style>`);
  242.  
  243. // collate the button bar
  244. let buttonBar = document.createElement('ul');
  245. $(buttonBar).addClass('actions comment-format');
  246. for (let c of config) {
  247. let li = document.createElement('li');
  248. li.title = c[1].text;
  249. li.innerHTML = `<a class="${c[0]}">${ (c[1].icon === "") ? c[1].text : c[1].icon}</a>`;
  250. if (c[1].icon !== "") $(li).addClass("fontawe");
  251. $(buttonBar).append(li);
  252. }
  253. $(buttonBar).find('a').on('click', function(e) {
  254. e.cancelBubble = true;
  255. e.preventDefault();
  256. insert_format(e.target);
  257. });
  258.  
  259. // preview box
  260. let preview = `<div class='comment-preview userstuff' title='Comment Preview (approximate)'></div>`;
  261.  
  262. // click event function called with the button <a> that was clicked (so we know which textarea to insert it to)
  263. function insert_format(elm) {
  264. let area = $(elm).parent().parent().next('textarea')[0]; // the textarea element we're dealing with
  265. let text = $(area).val(); // the original content of the comment box
  266. let cursor_start = area.selectionStart, cursor_end = area.selectionEnd; // any highlighted text
  267. let fmt = config.get(elm.className); // grab the formatting HTML corresponding to the clicked button
  268.  
  269. // set the comment box text with the new content, and focus back on it
  270. $(area).val(
  271. text.slice(0, cursor_start) + // text from before cursor position or highlight
  272. fmt.ins_pre + text.slice(cursor_start, cursor_end) + fmt.ins_app + // wrap any highlighted text in the formatting HTML
  273. text.slice(cursor_end) // text from after cursor position or highlight
  274. ).focus();
  275.  
  276. // set the cursor position to the same value so we don't highlight anymore
  277. let cursor_new =
  278. // if we only inserted format HTML, set it between the halves so you can enter the text to format
  279. (cursor_start == cursor_end) ? cursor_start + fmt.ins_pre.length :
  280. // if we highlighted, and this is a link (so the link text is already done), set the cursor into the href=""
  281. (elm.className == "link") ? cursor_start + fmt.ins_pre.length - 2 :
  282. // otherwise always set it at the end of the inserted text i.e. the same distance from the end as originally
  283. $(area).val().length - (text.length - cursor_end);
  284. area.selectionStart = area.selectionEnd = cursor_new;
  285.  
  286. // update the preview too, since the events don't fire through javascript
  287. update_preview(area);
  288. }
  289.  
  290. // input event function when anything changes in the textarea
  291. function update_preview(elm) {
  292. let prevbox = $(elm).siblings('div.comment-preview')[0];
  293. prevbox.innerHTML = parse_preview($(elm).val());
  294. }
  295.  
  296. // adding the button bar & preview box for any visible comment area (clone with events!)
  297. $('textarea[id^="comment_content_for"]')
  298. .before($(buttonBar).clone(true, true))
  299. .after($(preview).clone())
  300. .on('input', function(e) { update_preview(e.target); })
  301. // update the preview too, in case we're reloading the page with cached comment text
  302. .each(function() { update_preview(this); });
  303.  
  304. // adding the bar for any loaded comment areas
  305. // global AJAX listener but we're only interested in the calls that add the comment reply box
  306. XMLHttpRequest.prototype.getResponseHeader = function() { // jQuery ajaxSuccess method doesn't catch the reply pages
  307. if (!(this.readyState == 4 && this.status == 200)) return true;
  308. var xhrurl = this.responseURL;
  309. var params = (new URL(xhrurl)).searchParams;
  310.  
  311. // When replying to comments (on work or tag page)
  312. if (xhrurl.indexOf("comments/add_comment_reply?") !== -1) {
  313. $('textarea#comment_content_for_'+params.get("id"))
  314. .before($(buttonBar).clone(true, true))
  315. .after($(preview).clone())
  316. .on('input', function(e) { update_preview(e.target); });
  317. }
  318.  
  319. // When replying to inbox comments (floating box)
  320. else if (xhrurl.indexOf("inbox/reply?") !== -1) {
  321. $('textarea#comment_content_for_'+params.get("comment_id"))
  322. .before($(buttonBar).clone(true, true))
  323. .after($(preview).clone())
  324. .on('input', function(e) { update_preview(e.target); });
  325. }
  326.  
  327. // When editing a comment
  328. else if (xhrurl.indexOf("/comments/") !== -1 && xhrurl.indexOf("/edit") !== -1) {
  329. let commentid = xhrurl.match(/\d+/);
  330. $('li#comment_'+commentid[0]+' textarea[id^=comment_content_for_]')
  331. .before($(buttonBar).clone(true, true))
  332. .after($(preview).clone())
  333. .on('input', function(e) { update_preview(e.target); });
  334. update_preview($('li#comment_'+commentid[0]+' textarea[id^=comment_content_for_]'));
  335. }
  336. };
  337.  
  338. function parse_preview(content) {
  339. // if the comment box is still empty, show a simple placeholder
  340. if (content == "") return "<p><i>preview</i></p>";
  341.  
  342. // if there is comment text, turn double linebreaks into paragraphs and single linebreaks into <br>
  343. // linebreak compatibility
  344. const lbr = (content.indexOf("\r\n") > -1) ? "\r\n" :
  345. (content.indexOf("\r") > -1) ? "\r" : "\n";
  346. const splitPara = `${lbr}${lbr}`;
  347. const regexLine = new RegExp(`${lbr}`, "g");
  348.  
  349. // remove obvious issues: whitespaces between <li>'s, a <br> plus linebreak (while editing)
  350. content = content.replace(/<\/li>\W+<li>/ig, '</li><li>');
  351. content = content.replace(/<br \/>(\r\n|\r|\n)/ig, '<br />');
  352.  
  353. content = content.split(splitPara); // split content at each two linebreaks in a row
  354. content.forEach((v, i) => {
  355. v = v.replace(regexLine, "<br />"); // a single linebreak is replaced by a <br>
  356. content[i] = "<p>"+v.trim()+"</p>"; // two linebreaks are wrapped in a <p>
  357. });
  358. return content.join(lbr);
  359. }
  360.  
  361.  
  362. })(jQuery);
  363.  
  364. // helper function to determine whether a color (the background in use) is light or dark
  365. // https://awik.io/determine-color-bright-dark-using-javascript/
  366. function lightOrDark(color) {
  367.  
  368. // Variables for red, green, blue values
  369. var r, g, b, hsp;
  370.  
  371. // Check the format of the color, HEX or RGB?
  372. if (color.match(/^rgb/)) {
  373. // If RGB --> store the red, green, blue values in separate variables
  374. color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
  375. r = color[1];
  376. g = color[2];
  377. b = color[3];
  378. }
  379. else {
  380. // If hex --> Convert it to RGB: http://gist.github.com/983661
  381. color = +("0x" + color.slice(1).replace(color.length < 5 && /./g, '$&$&'));
  382. r = color >> 16;
  383. g = color >> 8 & 255;
  384. b = color & 255;
  385. }
  386.  
  387. // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
  388. hsp = Math.sqrt( 0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) );
  389.  
  390. // Using the HSP value, determine whether the color is light or dark
  391. if (hsp>127.5) { return 'light'; }
  392. else { return 'dark'; }
  393. }