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

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