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-03-17 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AO3: Comment Formatting and Preview
  3. // @namespace https://greasyfork.org/en/users/906106-escctrl
  4. // @version 2.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. // build GUI for chosen enable/disable of standard buttons
  72. let standardbuttons = '';
  73. config_std.forEach((val, key) => {
  74. 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"' : ""}>`;
  75. });
  76.  
  77. // reformat the stored custom buttons to match the standard
  78. let config_custom = new Map();
  79. custommap.forEach((val, key) => {
  80. val = JSON.parse(val); // turn the string into an array of 4x2 each
  81. let newval = {}; // turn the array into an object
  82. val.forEach((v) => {
  83. newval[v[0]] = v[1];
  84. });
  85. config_custom.set(key, newval);
  86. });
  87.  
  88. // build GUI for stored custom buttons
  89. let custombuttons = '';
  90. config_custom.forEach((val) => {
  91. custombuttons += `<div><button class="remove">-</button><input type="text" name="icon" value="${val.icon}"><input type="text" name="text" value="${val.text}">
  92. <input type="text" name="ins_pre" value="${val.ins_pre}"><input type="text" name="ins_app" value="${val.ins_app}"></div>`;
  93. });
  94.  
  95. // template for a blank row to add a custom button (is cloned before inserting into DOM)
  96. let newcustombutton = `<div><button class="remove">-</button><input type="text" name="icon" value="Icon"><input type="text" name="text" value="Title">
  97. <input type="text" name="ins_pre" value="Insert Before"><input type="text" name="ins_app" value="Insert After"></div>`;
  98.  
  99. $(cfg).html(`<form>
  100. <fieldset id='stdbutton'>
  101. <legend>Standard text formatting</legend>
  102. <p>Select the buttons you'd like to see as options on the button bar.</p>
  103. ${standardbuttons}
  104. </fieldset>
  105. <fieldset id='custombutton'>
  106. <legend>Custom HTML or text</legend>
  107. <p>Define custom buttons, which will insert HTML and/or text.</p>
  108. <ul><li>In the first field, choose <a href="https://fontawesome.com/v4/icons/">the Icon</a> you want on the button.<br />
  109. Copy its 4-letter Unicode (for example "f004" for the heart) into this field.</li>
  110. <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>
  111. <li>Put the text you want inserted around the cursor position into the Insert Before and Insert After fields.</li></ul>
  112. ${custombuttons}
  113. <div><button class="add">+</button></div>
  114. </fieldset>
  115. <p>Any changes only apply after reloading the page.</p>
  116. </form>`);
  117.  
  118. // attach it to the DOM so that selections work (but only if #main exists, else it might be a Retry Later error page)
  119. if ($("#main").length == 1) $("body").append(cfg);
  120.  
  121. // turn checkboxes and radiobuttons into pretty buttons
  122. $( "#cmtFmtDialog input[type='checkbox'], #cmtFmtDialog input[type='radio']" ).checkboxradio({ icon: false });
  123.  
  124. // optimizing the size of the GUI in case it's a mobile device
  125. let dialogwidth = parseInt($("body").css("width")); // parseInt ignores letters (px)
  126. dialogwidth = dialogwidth > 550 ? 550 : dialogwidth * 0.9;
  127.  
  128. // initialize the dialog (but don't open it)
  129. $( "#cmtFmtDialog" ).dialog({
  130. appendTo: "#main",
  131. modal: true,
  132. title: 'Comment Formatting Buttons',
  133. draggable: true,
  134. resizable: false,
  135. autoOpen: false,
  136. width: dialogwidth,
  137. position: {my:"center", at: "center top"},
  138. buttons: {
  139. Reset: deleteConfig,
  140. Save: storeConfig,
  141. Cancel: function() { $( "#cmtFmtDialog" ).dialog( "close" ); }
  142. }
  143. });
  144.  
  145. // event triggers if form is submitted with the <enter> key
  146. $( "#cmtFmtDialog form" ).on("submit", (e) => {
  147. e.preventDefault();
  148. storeConfig();
  149. });
  150.  
  151. // putting event triggers on buttons that will delete custom rows
  152. function evRemoveRow(el) {
  153. $(el).on("click", (e) => {
  154. e.cancelBubble = true;
  155. e.preventDefault();
  156. $(e.target).parent().remove(); // delete whole div
  157. });
  158. }
  159. // run it immediately on the stored custom buttons
  160. evRemoveRow($( "#cmtFmtDialog button.remove" ));
  161.  
  162. // putting event trigger on button that will add blank custom rows
  163. $( "#cmtFmtDialog button.add" ).on("click", (e) => {
  164. e.cancelBubble = true;
  165. e.preventDefault();
  166. // add a new blank row and attach the remove event again
  167. $(e.target).parent().before( $(newcustombutton).clone() );
  168. evRemoveRow($( "#cmtFmtDialog button.remove:last-of-type" ));
  169. });
  170.  
  171. function deleteConfig() {
  172. // deselects all buttons, empties all fields in the form
  173. $('#cmtFmtDialog form').trigger("reset");
  174. $('#cmtFmtDialog button.remove').trigger("click");
  175.  
  176. // deletes the localStorage
  177. localStorage.removeItem('cmtfmtstandard');
  178. localStorage.removeItem('cmtfmtcustom');
  179.  
  180. $( "#cmtFmtDialog" ).dialog( "close" );
  181. }
  182.  
  183. function storeConfig() {
  184. // build a Map() for enabled standard buttons => button -> true/false
  185. let storestd = new Map();
  186. $( "#cmtFmtDialog #stdbutton [name]" ).each(function() { storestd.set( $(this).prop('name'), String($(this).prop('checked')) ); });
  187. localStorage.setItem('cmtfmtstandard', JSON.stringify(Array.from(storestd.entries())));
  188.  
  189. // build a Map() for the custom buttons => custom# -> { icon: X, text: X, ins_pre: X, ins_app: X }
  190. let storecustom = new Map();
  191. $( "#cmtFmtDialog #custombutton div:has(input)" ).each((i, div) => {
  192. let parts = new Map();
  193. $(div).find('[name]').each(function() { parts.set( $(this).prop('name'), $(this).prop('value') ); });
  194. storecustom.set('custom'+i, JSON.stringify(Array.from(parts.entries())));
  195. });
  196. localStorage.setItem('cmtfmtcustom', JSON.stringify(Array.from(storecustom.entries())));
  197.  
  198. $( "#cmtFmtDialog" ).dialog( "close" );
  199. }
  200.  
  201. /* CREATING THE LINK TO OPEN THE CONFIGURATION DIALOG */
  202.  
  203. // if no other script has created it yet, write out a "Userscripts" option to the main navigation
  204. if ($('#scriptconfig').length == 0) {
  205. $('#header ul.primary.navigation li.dropdown').last()
  206. .after(`<li class="dropdown" id="scriptconfig">
  207. <a class="dropdown-toggle" href="/" data-toggle="dropdown" data-target="#">Userscripts</a>
  208. <ul class="menu dropdown-menu"></ul></li>`);
  209. }
  210. // then add this script's config option to navigation dropdown
  211. $('#scriptconfig .dropdown-menu').append(`<li><a href="javascript:void(0);" id="opencfg_cmtfmt">Comment Formatting Buttons</a></li>`);
  212.  
  213. // on click, open the configuration dialog
  214. $("#opencfg_cmtfmt").on("click", function(e) {
  215. $( "#cmtFmtDialog" ).dialog('open');
  216. });
  217.  
  218. /*********************************************************
  219. COMMENT BAR AND PREVIEW FUNCTIONALITY
  220. *********************************************************/
  221.  
  222. // merge the enabled standard and custom buttons into one list
  223. let config = new Map();
  224. config_std.forEach((val, key) => { if (standardmap.get(key)==="true" || standardmap.size == 0) config.set(key, val); });
  225. config_custom.forEach((val, key) => {
  226. if (val.icon !== "") val.icon = `&#x${val.icon};`; // add what Font Awesome needs to display properly
  227. config.set(key, val);
  228. });
  229.  
  230. $("head").append(`<style type="text/css"> ul.comment-format { font-family: FontAwesome, sans-serif; float: left; }
  231. ul.comment-format a { cursor: default; }
  232. ul.comment-format .fontawe { font-family: FontAwesome, sans-serif; }
  233. div.comment-preview.userstuff { border: 1px inset #f0f0f0; min-height: 1em; padding: 0.2em 1em; line-height: 1.5; } </style>`);
  234.  
  235. // collate the button bar
  236. let buttonBar = document.createElement('ul');
  237. $(buttonBar).addClass('actions comment-format');
  238. for (let c of config) {
  239. let li = document.createElement('li');
  240. li.title = c[1].text;
  241. li.innerHTML = `<a class="${c[0]}">${ (c[1].icon === "") ? c[1].text : c[1].icon}</a>`;
  242. if (c[1].icon !== "") $(li).addClass("fontawe");
  243. $(buttonBar).append(li);
  244. }
  245. $(buttonBar).find('a').on('click', function(e) {
  246. e.cancelBubble = true;
  247. e.preventDefault();
  248. insert_format(e.target);
  249. });
  250.  
  251. // preview box template (will be cloned when inserting into DOM)
  252. let preview = `<div class='comment-preview userstuff' title='Comment Preview (approximate)'></div>`;
  253.  
  254. // click event function called with the button <a> that was clicked (so we know which textarea to insert it to)
  255. function insert_format(elm) {
  256. let area = $(elm).parent().parent().next('textarea')[0]; // the textarea element we're dealing with
  257. let text = $(area).val(); // the original content of the comment box
  258. let cursor_start = area.selectionStart, cursor_end = area.selectionEnd; // any highlighted text
  259. let fmt = config.get(elm.className); // grab the formatting HTML corresponding to the clicked button
  260.  
  261. // set the comment box text with the new content, and focus back on it
  262. $(area).val(
  263. text.slice(0, cursor_start) + // text from before cursor position or highlight
  264. fmt.ins_pre + text.slice(cursor_start, cursor_end) + fmt.ins_app + // wrap any highlighted text in the formatting HTML
  265. text.slice(cursor_end) // text from after cursor position or highlight
  266. ).focus();
  267.  
  268. // set the cursor position to the same value so we don't highlight anymore
  269. let cursor_new =
  270. // if we only inserted format HTML, set it between the halves so you can enter the text to format
  271. (cursor_start == cursor_end) ? cursor_start + fmt.ins_pre.length :
  272. // if we highlighted, and this is a link (so the link text is already done), set the cursor into the href=""
  273. (elm.className == "link") ? cursor_start + fmt.ins_pre.length - 2 :
  274. // otherwise always set it at the end of the inserted text i.e. the same distance from the end as originally
  275. $(area).val().length - (text.length - cursor_end);
  276. area.selectionStart = area.selectionEnd = cursor_new;
  277.  
  278. // manually trigger the value-has-changed event so the preview updates (not calling update_preview directly as it would fail on Sticky Comment Box)
  279. $(area).trigger('input');
  280. }
  281.  
  282. // function called when anything changes (input event trigger) in the textarea
  283. function update_preview(elm) {
  284. let prevbox = $(elm).siblings('div.comment-preview')[0];
  285. prevbox.innerHTML = parse_preview($(elm).val());
  286. }
  287.  
  288. // adding the button bar & preview box for any visible comment area (clone with events!)
  289. $('textarea[id^="comment_content_for"]')
  290. .before($(buttonBar).clone(true, true))
  291. .after($(preview).clone())
  292. .on('input', function(e) { update_preview(e.target); })
  293. .each(function() { update_preview(this); }); // update the preview for reloaded pages with cached comment text
  294.  
  295. // Support for Sticky Comment Box!
  296. // if this script executes first, we may have to wait for the Sticky Comment Box to appear in the DOM
  297. if ($('#float_cmt_dlg').length == 0) {
  298. const observer = new MutationObserver(function(mutList, obs) {
  299. for (const mut of mutList) { for (const node of mut.addedNodes) {
  300. // check if the added node is our comment box
  301. if (node.id == 'float_cmt_dlg') {
  302. obs.disconnect(); // stop listening immediately, we have what we needed
  303. // add the buttonbar to the Sticky Comment Box (it doesn't get a preview field to save space)
  304. $('#float_cmt_userinput textarea').before($(buttonBar).clone(true, true).css('font-size', '80%'));
  305. }
  306. }}
  307. });
  308.  
  309. // listening to as few changes as possible: only direct children of <body>
  310. observer.observe($('body').get(0), { attributes: false, childList: true, subtree: false });
  311.  
  312. // failsafe: stop listening after 5 seconds (in case the other script isn't running)
  313. // this will always execute even if the box was already found and the observer disconnected previously
  314. let timeout = setTimeout(() => {
  315. observer.disconnect();
  316. }, 5 * 1000);
  317. }
  318. // when the Sticky Comment Box script executed first and the textarea is already there, we immediately add the button bar
  319. else $('#float_cmt_userinput textarea').before($(buttonBar).clone(true, true).css('font-size', '80%'));
  320.  
  321. // adding the bar for any loaded comment areas
  322. // global AJAX listener but we're only interested in the calls that add the comment reply box
  323. XMLHttpRequest.prototype.getResponseHeader = function() { // jQuery ajaxSuccess method doesn't catch the reply pages
  324. if (!(this.readyState == 4 && this.status == 200)) return true;
  325. var xhrurl = this.responseURL;
  326. var params = (new URL(xhrurl)).searchParams;
  327.  
  328. // When replying to comments (on work or tag page)
  329. if (xhrurl.indexOf("comments/add_comment_reply?") !== -1) {
  330. $('textarea#comment_content_for_'+params.get("id"))
  331. .before($(buttonBar).clone(true, true))
  332. .after($(preview).clone())
  333. .on('input', function(e) { update_preview(e.target); });
  334. }
  335.  
  336. // When replying to inbox comments (floating box)
  337. else if (xhrurl.indexOf("inbox/reply?") !== -1) {
  338. $('textarea#comment_content_for_'+params.get("comment_id"))
  339. .before($(buttonBar).clone(true, true))
  340. .after($(preview).clone())
  341. .on('input', function(e) { update_preview(e.target); });
  342. }
  343.  
  344. // When editing a comment
  345. else if (xhrurl.indexOf("/comments/") !== -1 && xhrurl.indexOf("/edit") !== -1) {
  346. let commentid = xhrurl.match(/\d+/);
  347. $('li#comment_'+commentid[0]+' textarea[id^=comment_content_for_]')
  348. .before($(buttonBar).clone(true, true))
  349. .after($(preview).clone())
  350. .on('input', function(e) { update_preview(e.target); })
  351. .each(function() { update_preview(this); }); // update the preview with the existing comment text
  352. }
  353. };
  354.  
  355. function parse_preview(content) {
  356. // if the comment box is still empty, show a simple placeholder
  357. if (content == "") return "<p><i>preview</i></p>";
  358.  
  359. // if there is comment text, turn double linebreaks into paragraphs and single linebreaks into <br>
  360. // linebreak compatibility
  361. const lbr = (content.indexOf("\r\n") > -1) ? "\r\n" :
  362. (content.indexOf("\r") > -1) ? "\r" : "\n";
  363.  
  364. // remove obvious issues: whitespaces between <li>'s, a <br> plus linebreak (while editing)
  365. content = content.replace(/<\/li>\W+<li>/ig, '</li><li>');
  366. content = content.replace(/<br \/>(\r\n|\r|\n)/ig, '<br />');
  367.  
  368. content = content.split(`${lbr}${lbr}`); // split content at each two linebreaks in a row
  369. const regexLine = new RegExp(`${lbr}`, "g");
  370. content.forEach((v, i) => {
  371. v = v.replace(regexLine, "<br />"); // a single linebreak is replaced by a <br>
  372. content[i] = "<p>"+v.trim()+"</p>"; // two linebreaks are wrapped in a <p>
  373. });
  374. return content.join(lbr);
  375. }
  376.  
  377. })(jQuery);
  378.  
  379. // helper function to determine whether a color (the background in use) is light or dark
  380. // https://awik.io/determine-color-bright-dark-using-javascript/
  381. function lightOrDark(color) {
  382. var r, g, b, hsp;
  383. if (color.match(/^rgb/)) { color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
  384. r = color[1]; g = color[2]; b = color[3]; }
  385. else { color = +("0x" + color.slice(1).replace(color.length < 5 && /./g, '$&$&'));
  386. r = color >> 16; g = color >> 8 & 255; b = color & 255; }
  387. hsp = Math.sqrt( 0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) );
  388. if (hsp>127.5) { return 'light'; } else { return 'dark'; }
  389. }