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

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