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-18 提交的版本,檢視 最新版本

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