MSPFA extras

Adds custom quality of life features to MSPFA.

当前为 2020-10-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name MSPFA extras
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.7.2
  5. // @description Adds custom quality of life features to MSPFA.
  6. // @author seymour schlong
  7. // @icon https://pipe.miroware.io/5b52ba1d94357d5d623f74aa/mspfa/ico.png
  8. // @icon64 https://pipe.miroware.io/5b52ba1d94357d5d623f74aa/mspfa/ico.png
  9. // @match https://mspfa.com/
  10. // @match https://mspfa.com/*/
  11. // @match https://mspfa.com/*/?*
  12. // @match https://mspfa.com/?s=*
  13. // @match https://mspfa.com/my/*
  14. // @match https://mspfa.com/random/
  15. // @exclude https://mspfa.com/js/*
  16. // @exclude https://mspfa.com/css/*
  17. // @grant none
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. 'use strict';
  22.  
  23. const currentVersion = "1.7.2";
  24. console.log(`MSPFA extras script v${currentVersion} by seymour schlong`);
  25.  
  26. const debug = false;
  27.  
  28. /**
  29. * https://github.com/GrantGryczan/MSPFA/projects/1?fullscreen=true
  30. * Github to-do completion list (and other stuff too)
  31. *
  32. * https://github.com/GrantGryczan/MSPFA/issues/26 - Dropdown menu - February 23rd, 2020
  33. * https://github.com/GrantGryczan/MSPFA/issues/18 - MSPFA themes - February 23rd, 2020
  34. * https://github.com/GrantGryczan/MSPFA/issues/32 - Adventure creation dates - February 23rd, 2020
  35. * https://github.com/GrantGryczan/MSPFA/issues/32 - User creation dates - February 23rd, 2020
  36. * https://github.com/GrantGryczan/MSPFA/issues/40 - Turn certain buttons into links - July 21st, 2020
  37. * https://github.com/GrantGryczan/MSPFA/issues/41 - Word and character count - July 21st, 2020
  38. * https://github.com/GrantGryczan/MSPFA/issues/57 - Default spoiler values - August 7th, 2020
  39. * https://github.com/GrantGryczan/MSPFA/issues/62 - Buttonless spoilers - August 7th, 2020
  40. * https://github.com/GrantGryczan/MSPFA/issues/52 - Hash URLs - August 8th, 2020
  41. * - Page drafts - August 8th, 2020
  42. * - Edit pages button - August 8th, 2020
  43. * - Image preloading - August 20th, 2020
  44. * https://github.com/GrantGryczan/MSPFA/issues/19 - Manage game saves - August 22nd, 2020
  45. *
  46. * Extension to-do... maybe...
  47. *
  48. * If trying to save a page and any other save button is not disabled, ask the user if they would rather Save All instead, or prompt to disable update notifications.
  49. * When adding a new page, store it in an array and if that array length is > 1 when someone tries to save, prompt them to press Save All?
  50. */
  51.  
  52. // A general function that allows for waiting until a certain element appears on the page.
  53. const pageLoad = (fn, length) => {
  54. const interval = setInterval(() => {
  55. if (fn()) clearInterval(interval);
  56. }, length ? length*1000 : 500);
  57. };
  58.  
  59. // Saves the options data for the script.
  60. const saveData = (data) => {
  61. localStorage.mspfaextra = JSON.stringify(data);
  62. if (debug) {
  63. console.log('Settings:');
  64. console.log(data);
  65. }
  66. };
  67.  
  68. // Saves the data for drafts
  69. const saveDrafts = (data) => {
  70. localStorage.mspfadrafts = JSON.stringify(data);
  71. if (debug) {
  72. console.log('Drafts:');
  73. console.log(data);
  74. }
  75. };
  76.  
  77. // Encases an element within a link
  78. const addLink = (elm, url, target) => {
  79. const link = document.createElement('a');
  80. link.href = url;
  81. link.draggable = false;
  82. if (elm.parentNode) elm.parentNode.insertBefore(link, elm);
  83. if (target) link.target = target;
  84. link.appendChild(elm);
  85. return link;
  86. };
  87.  
  88. // Easy br element
  89. const newBr = () => {
  90. return document.createElement('br');
  91. }
  92.  
  93. // Make creating label elements easier
  94. const createLabel = (text, id) => {
  95. const newLabel = document.createElement('label');
  96. newLabel.textContent = text;
  97. newLabel.setAttribute('for', id);
  98. return newLabel;
  99. }
  100.  
  101. let settings = {};
  102. let drafts = {};
  103.  
  104. const defaultSettings = {
  105. autospoiler: false,
  106. style: 0,
  107. styleURL: "",
  108. night: false,
  109. auto502: true,
  110. textFix: false,
  111. pixelFix: false,
  112. intro: false,
  113. commandScroll: false,
  114. preload: true,
  115. dialogKeys: true,
  116. dialogFocus: false,
  117. spoilerValues: {}
  118. }
  119.  
  120. let pageLoaded = false;
  121.  
  122. const loadDrafts = () => {
  123. if (localStorage.mspfadrafts) {
  124. drafts = JSON.parse(localStorage.mspfadrafts);
  125. }
  126. }
  127. loadDrafts();
  128.  
  129. // Load any previous settings from localStorage
  130. if (localStorage.mspfaextra) {
  131. Object.assign(settings, JSON.parse(localStorage.mspfaextra));
  132.  
  133. // Get draft data from settings
  134. if (typeof settings.drafts === "object") {
  135. if (Object.keys(settings.drafts).length > 0 && Object.keys(drafts).length === 0) {
  136. drafts = settings.drafts;
  137. }
  138. }
  139. saveDrafts(drafts);
  140. }
  141.  
  142. // If any settings are undefined, re-set to their default state. (For older users when new things get stored)
  143. const checkSettings = () => {
  144. const defaultSettingsKeys = Object.keys(defaultSettings);
  145. for (let i = 0; i < defaultSettingsKeys.length; i++) {
  146. if (typeof settings[defaultSettingsKeys[i]] === "undefined") {
  147. settings[defaultSettingsKeys[i]] = defaultSettings[defaultSettingsKeys[i]];
  148. }
  149. }
  150. saveData(settings);
  151. }
  152.  
  153. checkSettings();
  154.  
  155. if (GM_info && GM_info.scriptHandler !== "Tampermonkey" && !settings.warned) {
  156. alert(`It appears that you're running the MSPFA extras script with ${GM_info.scriptHandler}.\nUnfortunately, this script cannot run at its full potential because of that.\nTry switching to Tampermonkey if you want to use more of the features!\n(this message will only appear once.)`);
  157. settings.warned = true;
  158. saveData(settings);
  159. }
  160.  
  161. // Scrolls you to where you need to be
  162. const hashSearch = location.href.replace(location.origin + location.pathname, '').replace(location.search, '');
  163. if (hashSearch !== '') {
  164. pageLoad(() => {
  165. const idElement = document.querySelector(hashSearch);
  166. if (idElement) {
  167. const selected = document.querySelector(hashSearch);
  168. selected.scrollIntoView();
  169. selected.style.outline = '3px solid black';
  170. selected.style.transition = '0.5s';
  171. pageLoad(() => {
  172. if (pageLoaded) {
  173. selected.style.outline = '0px solid black';
  174. }
  175. });
  176.  
  177. return true;
  178. }
  179. }, 1);
  180. }
  181.  
  182. // Ripped shamelessly right from mspfa lol (URL search parameters -- story ID, page num, etc.)
  183. let rawParams;
  184. if (location.href.indexOf("#") != -1) {
  185. rawParams = location.href.slice(0, location.href.indexOf("#"));
  186. } else {
  187. rawParams = location.href;
  188. }
  189. if (rawParams.indexOf("?") != -1) {
  190. rawParams = rawParams.slice(rawParams.indexOf("?") + 1).split("&");
  191. } else {
  192. rawParams = [];
  193. }
  194. const params = {};
  195. for (let i = 0; i < rawParams.length; i++) {
  196. try {
  197. const p = rawParams[i].split("=");
  198. params[p[0]] = decodeURIComponent(p[1]);
  199. } catch (err) {}
  200. }
  201.  
  202. if (debug) {
  203. console.log('URL parameters:');
  204. console.log(params);
  205. }
  206.  
  207. // Functions to get/change data from the console
  208. window.MSPFAe = {
  209. getSettings: () => {
  210. return settings;
  211. },
  212. getSettingsString: (formatted) => {
  213. if (formatted) {
  214. console.log(JSON.stringify(settings, null, 4));
  215. } else {
  216. console.log(JSON.stringify(settings));
  217. }
  218. },
  219. getDrafts: () => {
  220. loadDrafts();
  221. return drafts;
  222. },
  223. getDraftsString: (formatted) => {
  224. loadDrafts();
  225. if (formatted) {
  226. console.log(JSON.stringify(drafts, null, 4));
  227. } else {
  228. console.log(JSON.stringify(drafts));
  229. }
  230. },
  231. changeSettings: (newSettings) => {
  232. console.log('Settings updated');
  233. console.log(settings);
  234. Object.assign(settings, newSettings);
  235. saveData(settings);
  236. },
  237. changeSettingsString: (fullString) => {
  238. try {
  239. JSON.parse(fullString);
  240. } catch (err) {
  241. console.error(err);
  242. return;
  243. }
  244. settings = JSON.parse(fullString);
  245. checkSettings();
  246. console.log(settings);
  247. },
  248. getParams: params
  249. }
  250.  
  251. // Error reloading
  252. window.addEventListener("load", () => {
  253. // Reload the page if 502 CloudFlare error page appears
  254. if (settings.auto502 && document.querySelector('#cf-wrapper')) {
  255. window.location.reload();
  256. }
  257.  
  258. // Wait five seconds, then refresh the page
  259. if (document.body.textContent === "Your client is sending data to MSPFA too quickly. Wait a moment before continuing.") {
  260. setTimeout(() => {
  261. window.location.reload();
  262. }, 5000);
  263. }
  264.  
  265. pageLoaded = true;
  266. });
  267.  
  268. // Delete any unchanged spoiler values
  269. if (location.pathname !== "/my/stories/pages/") {
  270. // Go through spoiler values and remove any that aren't unique
  271. Object.keys(settings.spoilerValues).forEach(adventure => {
  272. if (settings.spoilerValues[adventure].open === "Show" && settings.spoilerValues[adventure].close === "Hide") {
  273. delete settings.spoilerValues[adventure];
  274. } else if (settings.spoilerValues[adventure].open === '' && settings.spoilerValues[adventure].close === '') {
  275. delete settings.spoilerValues[adventure];
  276. }
  277. });
  278. }
  279.  
  280. const styleOptions = ["Standard", "Low Contrast", "Light", "Dark", "Felt", "Trickster", "Custom"];
  281. const styleUrls = ['', '/css/theme1.css', '/css/theme2.css', 'https://pipe.miroware.io/5b52ba1d94357d5d623f74aa/mspfa/themes/dark.css', '/css/theme4.css', '/css/theme5.css'];
  282.  
  283. const createDropdown = (parent, explore) => {
  284. const dropDiv = document.createElement('div');
  285. dropDiv.className = 'dropdown';
  286. dropDiv.style.display = 'inline-block';
  287.  
  288. const dropContent = document.createElement('div');
  289. dropContent.className = 'dropdown-content';
  290. dropContent.style.display = 'none';
  291.  
  292. if (!explore) {
  293. dropDiv.addEventListener('mouseenter', evt => {
  294. dropContent.style.display = 'block';
  295. dropContent.style.color = getComputedStyle(parent).color;
  296. dropContent.querySelectorAll('a').forEach(link => {
  297. link.style.color = getComputedStyle(parent).color;
  298. });
  299. });
  300. dropDiv.addEventListener('mouseleave', evt => {
  301. dropContent.style.display = 'none';
  302. });
  303. }
  304.  
  305. parent.parentNode.insertBefore(dropDiv, parent);
  306. dropDiv.appendChild(parent);
  307. dropDiv.appendChild(dropContent);
  308. return [dropDiv, dropContent];
  309. }
  310.  
  311. // "MY MSPFA" dropdown
  312. const myLink = document.querySelector('nav a[href="/my/"]');
  313. if (myLink) {
  314. const dropContent = createDropdown(myLink)[1];
  315.  
  316. const dLinks = [];
  317. dLinks[0] = [ 'Messages', 'My Adventures', 'Settings' ];
  318. dLinks[1] = [ '/my/messages/', '/my/stories/', '/my/settings/' ];
  319.  
  320. for (let i = 0; i < dLinks[0].length; i++) {
  321. const newLink = document.createElement('a');
  322. newLink.textContent = dLinks[0][i];
  323. newLink.href = dLinks[1][i];
  324. dropContent.appendChild(newLink);
  325. }
  326.  
  327. // Append "My Profile" to the dropdown list if you're signed in
  328. pageLoad(() => {
  329. if (window.MSPFA) {
  330. if (window.MSPFA.me.n) {
  331. if (settings.dropFav) {
  332. const newFavLink = document.createElement('a');
  333. newFavLink.textContent = "My Favourites";
  334. newFavLink.href = `/favs/?u=${window.MSPFA.me.i}`;
  335. dropContent.appendChild(newFavLink);
  336. }
  337. const newMyLink = document.createElement('a');
  338. newMyLink.textContent = "My Profile";
  339. newMyLink.href = `/user/?u=${window.MSPFA.me.i}`;
  340. dropContent.appendChild(newMyLink);
  341.  
  342. // Move SETTINGS to the bottom
  343. dropContent.appendChild(dropContent.querySelectorAll('a')[2]);
  344. return true;
  345. }
  346. }
  347. });
  348. }
  349.  
  350. // "RANDOM" dropdown
  351. const randomLink = document.querySelector('nav a[href="/random/"]');
  352. if (randomLink) {
  353. // Thank you @MadCreativity 🙏
  354. const dropContent = createDropdown(randomLink)[1];
  355.  
  356. (async () => {
  357. const dLinks = [];
  358. dLinks[0] = [ 'Recent ongoing' ];
  359. dLinks[1] = [ await fetch(`https://mspfa-extras-server.herokuapp.com/api/random`).then(e => e.text()) ];
  360.  
  361. for (let i = 0; i < dLinks[0].length; i++) {
  362. const newLink = document.createElement('a');
  363. newLink.textContent = dLinks[0][i];
  364. newLink.href = dLinks[1][i];
  365. dropContent.appendChild(newLink);
  366. }
  367. })()
  368. }
  369.  
  370. // "EXPLORE" dropdown
  371. const exploreLink = document.querySelector('nav a[href="/stories/"');
  372. if (exploreLink) {
  373. const dropdown = createDropdown(exploreLink, true);
  374. const dropDiv = dropdown[0];
  375. const dropContent = dropdown[1];
  376.  
  377. const exploreInput = document.createElement('input');
  378. Object.assign(exploreInput, { type: 'text', placeholder: 'Search...', id: 'dropdown-explore' });
  379. dropContent.appendChild(exploreInput);
  380. exploreInput.addEventListener('keydown', ke => {
  381. if (ke.code === 'Enter') {
  382. const searchLink = `/stories/?go=1&n=${encodeURIComponent(exploreInput.value)}&t=&h=14&o=favs&p=p&m=50&load=true`;
  383. if (ke.altKey || ke.ctrlKey) {
  384. window.open(searchLink, '_blank').focus();
  385. } else {
  386. location.href = searchLink;
  387. }
  388. return;
  389. }
  390. });
  391.  
  392. dropDiv.addEventListener('mouseenter', evt => {
  393. dropContent.style.display = 'block';
  394. });
  395. dropDiv.addEventListener('mouseleave', evt => {
  396. // If input is focused
  397. if (document.activeElement !== exploreInput) {
  398. dropContent.style.display = 'none';
  399. }
  400. });
  401. document.body.addEventListener('click', evt => {
  402. if (document.activeElement !== exploreInput) {
  403. dropContent.style.display = 'none';
  404. }
  405. });
  406. }
  407.  
  408. document.querySelector('header .mspfalogo').parentNode.draggable = false;
  409. addLink(document.querySelector('footer .mspfalogo'), 'javascript:void(0);');
  410.  
  411. // Message that shows when you first get the script
  412. const showIntroDialog = () => {
  413. const msg = window.MSPFA.parseBBCode('Hi! Thanks for installing this script!\n\nBe sure to check the [url=https://greasyfork.org/en/scripts/396798-mspfa-extras#additional-info]GreasyFork[/url] page to see a full list of features, and don\'t forget to check out your [url=https://mspfa.com/my/settings/#extraSettings]settings[/url] page to tweak things to how you want.\n\nIf you have any suggestions, or you find a bug, please be sure to let me know on Discord at [url=discord://discordapp.com/users/277928549866799125]@seymour schlong#3669[/url].\n\n[size=12]This dialog will only appear once. To view it again, click "View Script Message" at the bottom of the site.[/size]');
  414. window.MSPFA.dialog("MSPFA extras message", msg, ["Okay"]);
  415. }
  416.  
  417. // Check if show intro dialog has displayed
  418. if (!settings.intro) {
  419. pageLoad(() => {
  420. if (window.MSPFA) {
  421. showIntroDialog();
  422. settings.intro = true;
  423. saveData(settings);
  424. return true;
  425. }
  426. });
  427. }
  428.  
  429. const details = document.querySelector('#details');
  430.  
  431. // Add 'link' at the bottom to show the intro dialog again
  432. const introLink = document.createElement('a');
  433. introLink.textContent = 'View Script Message';
  434. introLink.href = 'javascript:void(0);';
  435. introLink.addEventListener('click', showIntroDialog);
  436. details.appendChild(introLink);
  437.  
  438. // vbar!!!!
  439. const vbar = document.createElement('span');
  440. Object.assign(vbar, {className: 'vbar', textContent: '|'});
  441. details.appendChild(document.createTextNode(' '));
  442. details.appendChild(vbar);
  443. details.appendChild(document.createTextNode(' '));
  444.  
  445. // if you really enjoy the script and has some extra moneys 🥺
  446. const donateLink = document.createElement('a');
  447. donateLink.textContent = 'Donate';
  448. donateLink.href = 'https://ko-fi.com/ironbean';
  449. donateLink.target = "blank";
  450. details.appendChild(donateLink);
  451.  
  452. // Theme stuff
  453. const theme = document.createElement('link');
  454. Object.assign(theme, { id: 'theme', type: 'text/css', rel: 'stylesheet' });
  455. const updateTheme = (src) => {
  456. theme.href = src;
  457. }
  458. if (!document.querySelector('#theme')) {
  459. document.querySelector('head').appendChild(theme);
  460. if (settings.night) {
  461. updateTheme(styleUrls[3]);
  462. } else {
  463. updateTheme(settings.style == styleOptions.length - 1 ? settings.styleURL : styleUrls[settings.style]);
  464. }
  465. }
  466.  
  467. const pixelText = () => {
  468. return settings.pixelFix ? 'body { image-rendering: pixelated; image-rendering: -moz-crisp-edges; }' : '';
  469. }
  470.  
  471. // Dropdown menu and pixelated scaling
  472. const mspfaeCSS = document.createElement('link');
  473. Object.assign(mspfaeCSS, { id: 'script-css', type: 'text/css', rel: 'stylesheet', href: 'https://pipe.miroware.io/5b52ba1d94357d5d623f74aa/mspfa/mspfae.css' });
  474. document.querySelector('head').appendChild(mspfaeCSS);
  475.  
  476. const extraStyle = document.createElement('style');
  477. if (!document.querySelector('#extra-style')) {
  478. extraStyle.id = 'extra-style';
  479. extraStyle.textContent = pixelText();
  480. document.querySelector('head').appendChild(extraStyle);
  481. }
  482.  
  483. let nightSwitch = [];
  484.  
  485. // Enabling night mode.
  486. document.querySelector('footer .mspfalogo').addEventListener('click', evt => {
  487. settings.night = !settings.night;
  488. saveData(settings);
  489.  
  490. for (let i = 0; i < nightSwitch.length; i++) {
  491. clearTimeout(nightSwitch[i]);
  492. }
  493. nightSwitch = [];
  494.  
  495. // Transition to make it feel nicer on the eyes
  496. extraStyle.textContent = pixelText();
  497. extraStyle.textContent = pixelText() + ' *{transition:1.5s;}';
  498.  
  499. if (settings.night) {
  500. updateTheme(styleUrls[3]);
  501. } else {
  502. updateTheme(settings.style == styleOptions.length - 1 ? settings.styleURL : styleUrls[settings.style]);
  503. }
  504.  
  505. nightSwitch.push(setTimeout(() => {
  506. extraStyle.textContent = pixelText();
  507. }, 1500));
  508. });
  509.  
  510. // Enable keyboard controls for some dialog boxes (enter/esc to accept/close)
  511. const dialog = document.querySelector('#dialog');
  512. document.addEventListener('keydown', evt => {
  513. if (settings.dialogKeys && !dialog.textContent.includes('BBCode')) {
  514. if (dialog.style.display === '' && (evt.code === 'Enter' || evt.code === "Escape") && (document.activeElement === document.body || settings.dialogFocus)) {
  515. let buttons = dialog.querySelectorAll('button');
  516. if (buttons.length === 1) {
  517. buttons[0].click();
  518. } else if (buttons.length === 2) {
  519. if (buttons[0].textContent === 'Okay' && evt.code === "Enter") {
  520. buttons[0].click();
  521. }
  522. }
  523. if (["Cancel", "Close"].indexOf(buttons[buttons.length - 1].textContent) !== -1 && evt.code === "Escape") {
  524. buttons[buttons.length - 1].click();
  525. }
  526. }
  527. }
  528. });
  529.  
  530. if (location.pathname.includes('//')) {
  531. location.href = location.pathname.replace(/\/\//g, '/') + location.search;
  532. }
  533.  
  534. if (location.pathname === "/" || location.pathname === "/preview/") {
  535. if (location.search) {
  536. // Remove the current theme if the adventure has CSS (to prevent conflicts);
  537. if (settings.style > 0) {
  538. pageLoad(() => {
  539. if (window.MSPFA) {
  540. if (window.MSPFA.story && window.MSPFA.story.y && (window.MSPFA.story.y.toLowerCase().includes('import') || window.MSPFA.story.y.includes('{'))) {
  541. if (!settings.night) updateTheme('');
  542. return true;
  543. }
  544. }
  545. if (pageLoaded) return true;
  546. });
  547. }
  548.  
  549. // Preload adjacent pages
  550. if (settings.preload) {
  551. const preloadImages = document.createElement('div');
  552. preloadImages.id = 'preload';
  553. document.querySelector('#container').appendChild(preloadImages);
  554. window.MSPFA.slide.push(p => {
  555. preloadImages.innerHTML = '';
  556. if (window.MSPFA.story.p[p-2]) {
  557. let page = window.MSPFA.parseBBCode(window.MSPFA.story.p[p-2].b);
  558. page.querySelectorAll('img').forEach(image => {
  559. preloadImages.appendChild(image);
  560. });
  561. page.innerHTML = '';
  562. }
  563. if (window.MSPFA.story.p[p]) {
  564. let page = window.MSPFA.parseBBCode(window.MSPFA.story.p[p].b);
  565. page.querySelectorAll('img').forEach(image => {
  566. preloadImages.appendChild(image);
  567. });
  568. page.innerHTML = '';
  569. }
  570. });
  571. }
  572.  
  573. // Automatic spoiler opening
  574. if (settings.autospoiler) {
  575. window.MSPFA.slide.push((p) => {
  576. document.querySelectorAll('#slide .spoiler:not(.open) > div:first-child > input').forEach(sb => sb.click());
  577. });
  578. }
  579.  
  580. // Scroll up to the nav bar when changing page so you don't have to scroll down as much =)
  581. if (settings.commandScroll) {
  582. const heightTop = document.querySelector('nav').getBoundingClientRect().top - document.body.getBoundingClientRect().top;
  583. let temp = -2; // To prevent moving the page down when loading it for the first time
  584. window.MSPFA.slide.push((p) => {
  585. if (temp < 0) {
  586. temp++;
  587. } else {
  588. window.scroll(0, heightTop);
  589. }
  590. });
  591. }
  592.  
  593. // Show creation date
  594. pageLoad(() => {
  595. if (document.querySelector('#infobox tr td:nth-child(2)')) {
  596. document.querySelector('#infobox tr td:nth-child(2)').appendChild(document.createTextNode('Creation date: ' + new Date(window.MSPFA.story.d).toString().split(' ').splice(1, 3).join(' ')));
  597. return true;
  598. }
  599. });
  600.  
  601. // Hash scrolling and opening infobox or commmentbox
  602. if (['#infobox', '#commentbox', '#newcomment', '#latestpages'].indexOf(hashSearch) !== -1) {
  603. pageLoad(() => {
  604. if (document.querySelector(hashSearch)) {
  605. if (hashSearch === '#infobox') {
  606. document.querySelector('input[data-open="Show Adventure Info"]').click();
  607. } else if (hashSearch === '#commentbox' || hashSearch === '#newcomment') {
  608. document.querySelector('input[data-open="Show Comments"]').click();
  609. } else if (hashSearch === '#latestpages') {
  610. document.querySelector('input[data-open="Show Adventure Info"]').click();
  611. document.querySelector('input[data-open="Show Latest Pages"]').click();
  612. }
  613. return true;
  614. }
  615. });
  616. }
  617.  
  618. // Attempt to fix text errors
  619. if (settings.textFix && location.pathname !== "/preview/") {
  620. pageLoad(() => {
  621. if (window.MSPFA.story && window.MSPFA.story.p) {
  622. // russian/bulgarian is not possible =(
  623. const currentPage = parseInt(/^\?s(?:.*?)&p=([\d]*)$/.exec(location.search)[1]);
  624. const library = [
  625. ["&acirc;��", "'"],
  626. ["&Atilde;�", "Ñ"],
  627. ["&Atilde;&plusmn;", "ñ"],
  628. ["&Atilde;&sup3;", "ó"],
  629. ["&Atilde;&iexcl;", "á"],
  630. ["&Auml;�", "ą"],
  631. ["&Atilde;&shy;", "í"],
  632. ["&Atilde;&ordm;", "ú"],
  633. ["&Atilde;&copy;", "é"],
  634. ["&Aring;�", "ł"],
  635. ["&Aring;&frac14;", "ż"],
  636. ["&Acirc;&iexcl;", "¡"],
  637. ["&Acirc;&iquest;", "¿"],
  638. ["N&Acirc;&ordm;", "#"]
  639. ];
  640. // https://mspfa.com/?s=5280&p=51 -- unknown error
  641.  
  642. const replaceTerms = (p) => {
  643. library.forEach(term => {
  644. if (window.MSPFA.story.p[p]) {
  645. window.MSPFA.story.p[p].c = window.MSPFA.story.p[p].c.replace(new RegExp(term[0], 'g'), term[1]);
  646. window.MSPFA.story.p[p].b = window.MSPFA.story.p[p].b.replace(new RegExp(term[0], 'g'), term[1]);
  647. }
  648. });
  649. };
  650.  
  651. replaceTerms(currentPage-1);
  652.  
  653. window.MSPFA.slide.push(p => {
  654. replaceTerms(p);
  655. replaceTerms(p-2);
  656. });
  657. return true;
  658. }
  659. });
  660. }
  661.  
  662. // Turn buttons into links
  663. const pageButton = document.createElement('button');
  664. const pageLink = addLink(pageButton, `/my/stories/pages/?s=${params.s}#p${params.p}`);
  665. pageButton.className = 'pages edit major';
  666. pageButton.type = 'button';
  667. pageButton.title = 'Edit Pages';
  668.  
  669. // Edit pages button & button link
  670. pageLoad(() => {
  671. const infoButton = document.querySelector('.edit.major');
  672. if (infoButton) {
  673. pageLoad(() => {
  674. if (window.MSPFA.me.i) {
  675. infoButton.title = "Edit Info";
  676. infoButton.parentNode.insertBefore(pageLink, infoButton);
  677. infoButton.parentNode.insertBefore(document.createTextNode(' '), infoButton);
  678. addLink(infoButton, `/my/stories/info/?s=${params.s}`);
  679. pageButton.style.display = document.querySelector('.edit.major:not(.pages)').style.display;
  680.  
  681. // Change change page link when switching pages
  682. window.MSPFA.slide.push(p => {
  683. const newSearch = location.search.split('&p=');
  684. pageLink.href = `/my/stories/pages/?s=${params.s}#p${newSearch[1].split('#')[0]}`;
  685. });
  686. return true;
  687. }
  688. });
  689. addLink(document.querySelector('.rss.major'), `/rss/?s=${params.s}`);
  690. return true;
  691. }
  692. });
  693.  
  694. // Add "Reply" button next to comment gear
  695. setInterval(() => {
  696. if (document.querySelector('#commentbox > .spoiler.open')) {
  697. document.querySelectorAll('.gear').forEach(gear => {
  698. if (!gear.parentNode.querySelector('.reply')) {
  699. const replyDiv = document.createElement('div');
  700. replyDiv.className = 'reply';
  701. gear.insertAdjacentElement('afterEnd', replyDiv);
  702. gear.insertAdjacentHTML('afterEnd', '<span style="float: right"> </span>');
  703. const userID = gear.parentNode.parentNode.classList[2].replace('u', '');
  704.  
  705. replyDiv.addEventListener('click', () => {
  706. const commentBox = document.querySelector('#commentbox textarea');
  707. commentBox.value = `[user]${userID}[/user], ${commentBox.value}`;
  708. commentBox.focus();
  709. commentBox.parentNode.scrollIntoView();
  710. });
  711. }
  712. });
  713. }
  714. }, 500);
  715. }
  716. }
  717. else if (location.pathname === "/my/") {
  718. const parent = document.querySelector('#editstories').parentNode;
  719. const viewSaves = document.createElement('a');
  720. Object.assign(viewSaves, { id: 'viewsaves', className: 'major', textContent: 'View Adventure Saves' });
  721.  
  722. parent.appendChild(viewSaves);
  723. parent.appendChild(newBr());
  724. parent.appendChild(newBr());
  725.  
  726. pageLoad(() => {
  727. if (window.MSPFA && window.MSPFA.me && window.MSPFA.me.i) {
  728. viewSaves.href = `/?s=36596&p=6`;
  729. return true;
  730. }
  731. });
  732.  
  733. document.querySelector('#editstories').classList.remove('alt');
  734. }
  735. else if (location.pathname === "/my/settings/") { // Custom settings
  736. const saveBtn = document.querySelector('#savesettings');
  737.  
  738. const table = document.querySelector("#editsettings tbody");
  739. let saveTr = table.querySelectorAll("tr");
  740. saveTr = saveTr[saveTr.length - 1];
  741.  
  742. const headerTr = document.createElement('tr');
  743. const header = document.createElement('th');
  744. Object.assign(header, { id: 'extraSettings', textContent: 'Extra Settings' });
  745. headerTr.appendChild(header);
  746.  
  747. const moreTr = document.createElement('tr');
  748. const more = document.createElement('td');
  749. more.textContent = "* This only applies to a select few older adventures that have had their text corrupted. Some punctuation is fixed, as well as regular characters with accents. Currently only some spanish/french is fixable. Russian/Bulgarian is not possible.";
  750. moreTr.appendChild(more);
  751.  
  752. const settingsTr = document.createElement('tr');
  753. const localMsg = document.createElement('span');
  754. const settingsTd = document.createElement('td');
  755. localMsg.innerHTML = "Because this is an extension, any data saved is only <b>locally</b> on this device.<br>Don't forget to <b>save</b> when you've finished making changes!";
  756. const plusTable = document.createElement('table');
  757. const plusTbody = document.createElement('tbody');
  758. plusTable.appendChild(plusTbody);
  759. settingsTd.appendChild(localMsg);
  760. settingsTd.appendChild(newBr());
  761. settingsTd.appendChild(newBr());
  762. settingsTd.appendChild(plusTable);
  763. settingsTr.appendChild(settingsTd);
  764.  
  765. plusTable.style = "text-align: center;";
  766.  
  767. // Create checkbox (soooo much better)
  768. const createCheckbox = (text, checked, id) => {
  769. const optionTr = plusTbody.insertRow(plusTbody.childNodes.length);
  770. const optionTextTd = optionTr.insertCell(0);
  771. const optionLabel = createLabel(text, id);
  772. const optionInputTd = optionTr.insertCell(1);
  773. const optionInput = document.createElement('input');
  774. optionInputTd.appendChild(optionInput);
  775.  
  776. optionTextTd.appendChild(optionLabel);
  777. optionInput.type = "checkbox";
  778. optionInput.checked = checked;
  779. optionInput.id = id;
  780.  
  781. return optionInput;
  782. }
  783.  
  784. const spoilerInput = createCheckbox("Automatically open spoilers:", settings.autospoiler, 'autospoiler');
  785. const preloadInput = createCheckbox("Preload images for the pages immediately before and after:", settings.preload, 'preload');
  786. const dropFavInput = createCheckbox("Adds \"My Favourites\" to the dropdown menu:", settings.dropFav, 'dropFav');
  787. const errorInput = createCheckbox("Automatically reload Cloudflare 502 error pages:", settings.auto502, 'auto502');
  788. const commandScrollInput = createCheckbox("Scroll back up to the nav bar when switching page:", settings.commandScroll, 'commandScroll');
  789. const dialogKeysInput = createCheckbox("Use enter/escape keys to accept/exit control some dialogs:", settings.dialogKeys, 'dialogKeys');
  790. const dialogFocusInput = createCheckbox("Let keys work while dialog isn't focused (above required):", settings.dialogFocus, 'dialogFocus');
  791. const pixelFixInput = createCheckbox("Change pixel scaling to nearest neighbour:", settings.pixelFix, 'pixelFix');
  792. const textFixInput = createCheckbox("Attempt to fix text errors (experimental)*:", settings.textFix, 'textFix');
  793.  
  794. const cssTr = plusTbody.insertRow(plusTbody.childNodes.length);
  795. const cssTextTd = cssTr.insertCell(0);
  796. const cssSelectTd = cssTr.insertCell(1);
  797. const cssSelect = document.createElement('select');
  798. cssSelectTd.appendChild(cssSelect);
  799.  
  800. cssTextTd.textContent = "Change style:";
  801.  
  802. const customTr = plusTbody.insertRow(plusTbody.childNodes.length);
  803. const customTextTd = customTr.insertCell(0);
  804. const customCssTd = customTr.insertCell(1);
  805. const customCssInput = document.createElement('input');
  806. customCssTd.appendChild(customCssInput);
  807.  
  808. customTextTd.textContent = "Custom CSS URL:";
  809. customCssInput.style.width = "99px";
  810. customCssInput.value = settings.styleURL;
  811.  
  812. styleOptions.forEach(o => cssSelect.appendChild(new Option(o, o)));
  813.  
  814. saveTr.parentNode.insertBefore(headerTr, saveTr);
  815. saveTr.parentNode.insertBefore(settingsTr, saveTr);
  816. saveTr.parentNode.insertBefore(moreTr, saveTr);
  817. cssSelect.selectedIndex = settings.style;
  818.  
  819. const buttonSpan = document.createElement('span');
  820. const draftButton = document.createElement('input');
  821. const spoilerButton = document.createElement('input');
  822. draftButton.value = 'Manage Drafts';
  823. draftButton.className = 'major';
  824. draftButton.type = 'button';
  825. spoilerButton.value = 'Manage Spoiler Values';
  826. spoilerButton.className = 'major';
  827. spoilerButton.type = 'button';
  828. buttonSpan.appendChild(draftButton);
  829. buttonSpan.appendChild(document.createTextNode(' '));
  830. buttonSpan.appendChild(spoilerButton);
  831. settingsTd.appendChild(buttonSpan);
  832.  
  833. const draftMsg = window.MSPFA.parseBBCode('Here you can manage the drafts that you have saved for your adventure(s).\n');
  834. const listTable = document.createElement('table');
  835. listTable.id = 'draft-table';
  836. const listTbody = document.createElement('tbody');
  837. listTable.appendChild(listTbody);
  838.  
  839. const draftsEmpty = () => {
  840. loadDrafts();
  841. let empty = true;
  842. Object.keys(drafts).forEach(adv => {
  843. if (empty) {
  844. const length = typeof drafts[adv].cachedTitle === "undefined" ? 0 : 1;
  845. if (Object.keys(drafts[adv]).length > length) {
  846. empty = false;
  847. }
  848. }
  849. });
  850. return empty;
  851. }
  852.  
  853. setInterval(() => {
  854. draftButton.disabled = draftsEmpty();
  855. }, 1000);
  856.  
  857. draftButton.addEventListener('click', () => {
  858. draftMsg.appendChild(listTable);
  859. listTbody.innerHTML = '';
  860. loadDrafts();
  861.  
  862. const addAdv = (story, name) => {
  863. const storyTr = listTbody.insertRow(listTable.rows);
  864. const titleLink = document.createElement('a');
  865. Object.assign(titleLink, { className: 'major', href: `/my/stories/pages/?s=${story}&click=d`, textContent: name, target: '_blank' });
  866. storyTr.insertCell(0).appendChild(titleLink);
  867. const deleteButton = document.createElement('input');
  868. Object.assign(deleteButton, { className: 'major', type: 'button', value: 'Delete' });
  869. storyTr.insertCell(1).appendChild(deleteButton);
  870.  
  871. deleteButton.addEventListener('click', () => {
  872. setTimeout(() => {
  873. window.MSPFA.dialog('Delete adventure draft?', document.createTextNode('Are you really sure?\nThis action cannot be undone!'), ["Yes", "No"], (output, form) => {
  874. if (output === "Yes") {
  875. loadDrafts();
  876. drafts[story] = {};
  877.  
  878. if (settings.drafts && settings.drafts[story]) {
  879. delete settings.drafts[story];
  880. saveData(settings);
  881. }
  882.  
  883. saveDrafts(drafts);
  884.  
  885. setTimeout(() => {
  886. draftButton.click();
  887. }, 1);
  888.  
  889. if (draftsEmpty) {
  890. draftButton.disabled = true;
  891. }
  892. }
  893. });
  894. }, 1);
  895. });
  896. }
  897.  
  898. Object.keys(drafts).forEach(adv => {
  899. const length = typeof drafts[adv].cachedTitle === "undefined" ? 0 : 1;
  900. if (Object.keys(drafts[adv]).length > length) {
  901. if (!!length) {
  902. addAdv(adv, drafts[adv].cachedTitle);
  903. }
  904. else {
  905. window.MSPFA.request(0, {
  906. do: "story",
  907. s: adv
  908. }, story => {
  909. if (typeof story !== "undefined") {
  910. console.log(story);
  911. addAdv(adv, story.n);
  912. }
  913. });
  914. }
  915. }
  916. });
  917.  
  918. window.MSPFA.dialog('Manage Drafts', draftMsg, ["Delete All", "Close"], (output, form) => {
  919. if (output === "Delete All") {
  920. setTimeout(() => {
  921. window.MSPFA.dialog('Delete all Drafts?', document.createTextNode('Are you really sure?\nThis action cannot be undone!'), ["Yes", "No"], (output, form) => {
  922. if (output === "Yes") {
  923. Object.keys(drafts).forEach(adv => {
  924. drafts[adv] = {};
  925. });
  926. saveDrafts(drafts);
  927.  
  928. if (typeof settings.drafts !== "undefined") {
  929. delete settings.drafts;
  930. saveData(settings);
  931. }
  932.  
  933. draftButton.disabled = true;
  934. }
  935. });
  936. }, 1);
  937. }
  938. });
  939. });
  940.  
  941. if (Object.keys(settings.spoilerValues).length === 0) {
  942. spoilerButton.disabled = true;
  943. }
  944.  
  945. const spoilerMsg = window.MSPFA.parseBBCode('Here you can manage the spoiler values that you have set for your adventure(s).\nClick on an adventure\'s title to see the values.\n');
  946.  
  947. spoilerButton.addEventListener('click', () => {
  948. spoilerMsg.appendChild(listTable);
  949. listTbody.innerHTML = '';
  950. Object.keys(settings.spoilerValues).forEach(adv => {
  951. window.MSPFA.request(0, {
  952. do: "story",
  953. s: adv
  954. }, story => {
  955. if (typeof story !== "undefined") {
  956. const storyTr = listTbody.insertRow(listTable.rows);
  957. const titleLink = document.createElement('a');
  958. Object.assign(titleLink, { className: 'major', href: `/my/stories/pages/?s=${adv}&click=s`, textContent: story.n, target: '_blank' });
  959. storyTr.insertCell(0).appendChild(titleLink);
  960. const deleteButton = document.createElement('input');
  961. Object.assign(deleteButton, { className: 'major', type: 'button', value: 'Delete' });
  962. storyTr.insertCell(1).appendChild(deleteButton);
  963.  
  964. deleteButton.addEventListener('click', () => {
  965. setTimeout(() => {
  966. window.MSPFA.dialog('Delete adventure spoilers?', document.createTextNode('Are you really sure?\nThis action cannot be undone!'), ["Yes", "No"], (output, form) => {
  967. if (output === "Yes") {
  968. delete settings.spoilerValues[adv];
  969. saveData(settings);
  970.  
  971. setTimeout(() => {
  972. spoilerButton.click();
  973. }, 1);
  974.  
  975. if (Object.keys(settings.spoilerValues).length === 0) {
  976. spoilerButton.disabled = true;
  977. }
  978. }
  979. });
  980. }, 1);
  981. });
  982. }
  983. });
  984. });
  985. window.MSPFA.dialog('Manage Spoiler Values', spoilerMsg, ["Delete All", "Close"], (output, form) => {
  986. if (output === "Delete All") {
  987. setTimeout(() => {
  988. window.MSPFA.dialog('Delete all Spoiler Values?', 'Are you sure you want to delete all spoiler values?\nThis action cannot be undone!', ["Yes", "No"], (output, form) => {
  989. if (output === "Yes") {
  990. settings.spoilerValues = {};
  991. saveData(settings);
  992. spoilerButton.disabled = true;
  993. }
  994. });
  995. }, 1);
  996. }
  997. });
  998. });
  999.  
  1000. // Add event listeners
  1001. plusTbody.querySelectorAll('input, select').forEach(elm => {
  1002. elm.addEventListener("change", () => {
  1003. saveBtn.disabled = false;
  1004. });
  1005. });
  1006.  
  1007. saveBtn.addEventListener('mouseup', () => {
  1008. settings.autospoiler = spoilerInput.checked;
  1009. settings.style = cssSelect.selectedIndex;
  1010. settings.styleURL = customCssInput.value;
  1011. settings.auto502 = errorInput.checked;
  1012. settings.textFix = textFixInput.checked;
  1013. settings.pixelFix = pixelFixInput.checked;
  1014. settings.dialogKeys = dialogKeysInput.checked;
  1015. settings.dialogFocus = dialogFocusInput.checked;
  1016. settings.commandScroll = commandScrollInput.checked;
  1017. settings.preload = preloadInput.checked;
  1018. settings.dropFav = dropFavInput.checked;
  1019. settings.night = false;
  1020. console.log(settings);
  1021. saveData(settings);
  1022.  
  1023. updateTheme(settings.style == styleOptions.length - 1 ? settings.styleURL : styleUrls[settings.style]);
  1024.  
  1025. extraStyle.textContent = pixelText() + ' *{transition:1s}';
  1026.  
  1027. extraStyle.textContent = pixelText();
  1028. setTimeout(() => {
  1029. extraStyle.textContent = pixelText();
  1030. }, 1000);
  1031. });
  1032. }
  1033. else if (location.pathname === "/my/messages/") { // New buttons
  1034. // Select all read messages button.
  1035. const selRead = document.createElement('input');
  1036. Object.assign(selRead, { value: 'Select Read', className: 'major', type: 'button' });
  1037.  
  1038. // On click, select all messages with the style attribute indicating it as read.
  1039. selRead.addEventListener('mouseup', () => {
  1040. document.querySelectorAll('td[style="border-left: 8px solid rgb(221, 221, 221);"] > input').forEach((m) => m.click());
  1041. });
  1042.  
  1043. // Select duplicate message (multiple update notifications).
  1044. const selDupe = document.createElement('input');
  1045. Object.assign(selDupe, { value: 'Select Same', className: 'major', type: 'button', style: 'margin-top: 6px' });
  1046.  
  1047. selDupe.addEventListener('mouseup', evt => {
  1048. const temp = document.querySelectorAll('#messages > tr');
  1049. const msgs = [];
  1050. for (let i = temp.length - 1; i >= 0; i--) {
  1051. msgs.push(temp[i]);
  1052. }
  1053. const titles = [];
  1054. msgs.forEach((msg) => {
  1055. const title = msg.querySelector('a.major').textContent;
  1056. // Select only adventure updates
  1057. if (/^New update: /.test(title)) {
  1058. if (titles.indexOf(title) === -1) {
  1059. if (msg.querySelector('td').style.cssText !== "border-left: 8px solid rgb(221, 221, 221);") {
  1060. titles.push(title);
  1061. }
  1062. } else {
  1063. msg.querySelector('input').click();
  1064. }
  1065. }
  1066. });
  1067. });
  1068.  
  1069. // Prune button
  1070. const pruneButton = document.createElement('input');
  1071. Object.assign(pruneButton, { type: 'button', value: 'Prune', className: 'major' });
  1072.  
  1073. pruneButton.addEventListener('click', () => {
  1074. const ageInput = document.createElement('input');
  1075. Object.assign(ageInput, { type: 'number', min: 1, max: 10, value: 1 });
  1076.  
  1077. const msgState = document.createElement('select');
  1078. ['all', 'all unread', 'all read'].forEach(option => {
  1079. const op = document.createElement('option');
  1080. op.textContent = option;
  1081. msgState.appendChild(op);
  1082. });
  1083.  
  1084. const timeUnit = document.createElement('select');
  1085. ['month(s)', 'week(s)', 'day(s)'].forEach(option => {
  1086. const op = document.createElement('option');
  1087. op.textContent = option;
  1088. timeUnit.appendChild(op);
  1089. });
  1090. timeUnit.childNodes[1].setAttribute('selected', 'selected');
  1091.  
  1092. const msg = document.createElement('span');
  1093. msg.appendChild(document.createTextNode('Prune '));
  1094. msg.appendChild(msgState);
  1095. msg.appendChild(document.createTextNode(' messages older than '));
  1096. msg.appendChild(ageInput);
  1097. msg.appendChild(timeUnit);
  1098.  
  1099. window.MSPFA.dialog('Prune messages', msg, ['Prune', 'Cancel'], (output, form) => {
  1100. if (output === 'Prune') {
  1101. document.querySelector('#messages').childNodes.forEach(node => {
  1102. if (node.firstChild.firstChild.checked) {
  1103. node.firstChild.firstChild.click();
  1104. }
  1105.  
  1106. const selectedState = msgState.selectedOptions[0].textContent;
  1107. const selectedUnit = timeUnit.selectedOptions[0].textContent;
  1108.  
  1109. if (selectedState === 'all unread') {
  1110. if (node.firstChild.style.borderLeftColor === 'rgb(221, 221, 221)') {
  1111. return;
  1112. }
  1113. }
  1114. else if (selectedState === 'all read') {
  1115. if (node.firstChild.style.borderLeftColor === 'rgb(92, 174, 223)') {
  1116. return;
  1117. }
  1118. }
  1119. const dateText = node.childNodes[2].childNodes[2].textContent.split(' - ');
  1120. const messageDate = new Date(dateText[dateText.length-1]);
  1121. const currentDate = Date.now();
  1122. const diff = Math.floor(Math.round((currentDate-messageDate)/(1000*60*60))/24); // Difference in days
  1123.  
  1124. if (selectedUnit === 'month(s)') diff = Math.floor(diff / 30);
  1125. else if (selectedUnit === 'week(s)') diff = Math.floor(diff / 7);
  1126.  
  1127. if (diff >= ageInput.value) {
  1128. node.firstChild.firstChild.click();
  1129. }
  1130. });
  1131.  
  1132. setTimeout(() => {
  1133. document.querySelector('input[value=Delete]').click();
  1134. }, 1);
  1135. }
  1136. });
  1137. });
  1138.  
  1139. // Maybe add a "Merge Updates" button?
  1140. // [Merge Updates] would create a list of updates, similar to [Select Same]
  1141.  
  1142. // Add buttons to the page.
  1143. const del = document.querySelector('#deletemsgs');
  1144. del.parentNode.appendChild(newBr());
  1145. del.parentNode.appendChild(selRead);
  1146. del.parentNode.appendChild(document.createTextNode(' '));
  1147. del.parentNode.appendChild(selDupe);
  1148. del.parentNode.appendChild(document.createTextNode(' '));
  1149. del.parentNode.appendChild(pruneButton);
  1150.  
  1151. // Click the green cube to open the update/comment in a new tab, and mark notification as read.
  1152. pageLoad(() => {
  1153. if (document.querySelector('#messages').childNodes.length > 0) {
  1154. if (document.querySelector('#messages').textContent === 'No new messages were found.') {
  1155. // Disable some buttons if there are no messages.
  1156. pruneButton.disabled = true;
  1157. selDupe.disabled = true;
  1158. return true;
  1159. } else {
  1160. document.querySelector('#messages').childNodes.forEach(node => {
  1161. if (node.textContent.includes('New update:') && node.textContent.includes('MS Paint Fan Adventures')) {
  1162. const link = addLink(node.querySelector('.cellicon'), node.querySelector('.spoiler a').href);
  1163. link.addEventListener('mouseup', () => {
  1164. const spoiler = node.querySelector('.spoiler');
  1165. const button = spoiler.querySelector('input');
  1166. spoiler.className = 'spoiler closed';
  1167. button.click();
  1168. button.click();
  1169. });
  1170. }
  1171. else if (node.textContent.includes('New comment on ') && node.textContent.includes('MS Paint Fan Adventures')) {
  1172. const link = addLink(node.querySelector('.cellicon'), node.querySelectorAll('.spoiler a')[1].href + '#commentbox');
  1173. link.addEventListener('mouseup', () => {
  1174. const spoiler = node.querySelector('.spoiler');
  1175. const button = spoiler.querySelector('input');
  1176. spoiler.className = 'spoiler closed';
  1177. button.click();
  1178. button.click();
  1179. });
  1180. }
  1181. });
  1182. return true;
  1183. }
  1184. }
  1185. });
  1186. }
  1187. else if (location.pathname === "/my/messages/new/" && location.search) { // Auto-fill user when linked from a user page
  1188. const recipientInput = document.querySelector('#addrecipient');
  1189. recipientInput.value = params.u;
  1190. pageLoad(() => {
  1191. const recipientButton = document.querySelector('#addrecipientbtn');
  1192. if (recipientButton) {
  1193. recipientButton.click();
  1194. if (recipientInput.value === "") { // If the button press doesn't work
  1195. return true;
  1196. }
  1197. }
  1198. });
  1199. }
  1200. else if (location.pathname === "/my/stories/") {
  1201. // Add links to buttons
  1202. pageLoad(() => {
  1203. const adventures = document.querySelectorAll('#stories tr');
  1204. if (adventures.length > 0) {
  1205. adventures.forEach(story => {
  1206. const buttons = story.querySelectorAll('input.major');
  1207. const id = story.querySelector('a').href.replace('https://mspfa.com/', '').replace('&p=1', '');
  1208. if (id) {
  1209. addLink(buttons[0], `/my/stories/info/${id}`);
  1210. addLink(buttons[1], `/my/stories/pages/${id}`);
  1211. addLink(story.querySelector('img'), `/${id}&p=1`);
  1212. }
  1213. });
  1214. return true;
  1215. }
  1216. if (pageLoaded) return true;
  1217. });
  1218.  
  1219. // Add user guides
  1220. const guides = ["A Guide To Uploading Your Comic To MSPFA", "MSPFA Etiquette", "Fanventure Guide for Dummies", "CSS Guide", "HTML and CSS Things", ];
  1221. const links = ["https://docs.google.com/document/d/17QI6Cv_BMbr8l06RrRzysoRjASJ-ruWioEtVZfzvBzU/edit?usp=sharing", "/?s=27631", "/?s=29299", "/?s=21099", "/?s=23711"];
  1222. const authors = ["Farfrom Tile", "Radical Dude 42", "nzar", "MadCreativity", "seymour schlong"];
  1223.  
  1224. const parentTd = document.querySelector('.container > tbody > tr:last-child > td');
  1225. const unofficial = parentTd.querySelector('span');
  1226. unofficial.textContent = "Unofficial Guides";
  1227. const guideTable = document.createElement('table');
  1228. const guideTbody = document.createElement('tbody');
  1229. guideTable.style.width = "100%";
  1230. guideTable.style.textAlign = "center";
  1231.  
  1232. guideTable.appendChild(guideTbody);
  1233. parentTd.appendChild(guideTable);
  1234.  
  1235. for (let i = 0; i < guides.length; i++) {
  1236. const guideTr = guideTbody.insertRow(i);
  1237. const guideTd = guideTr.insertCell(0);
  1238. const guideLink = document.createElement('a');
  1239. Object.assign(guideLink, { href: links[i], textContent: guides[i], className: 'major' });
  1240. guideTd.appendChild(guideLink);
  1241. guideTd.appendChild(newBr());
  1242. guideTd.appendChild(document.createTextNode('by '+authors[i]));
  1243. guideTd.appendChild(newBr());
  1244. guideTd.appendChild(newBr());
  1245. }
  1246. }
  1247. else if (location.pathname === "/my/stories/info/" && location.search) {
  1248. // Button links
  1249. addLink(document.querySelector('#userfavs'), `/readers/?s=${params.s}`);
  1250. addLink(document.querySelector('#editpages'), `/my/stories/pages/?s=${params.s}`);
  1251.  
  1252. // Download adventure data
  1253. if (params.s !== 'new') {
  1254. const downloadButton = document.createElement('input');
  1255. Object.assign(downloadButton, { className: 'major', value: 'Export Data', type: 'button', style: 'margin-top: 6px' });
  1256. const downloadLink = document.createElement('a');
  1257. window.MSPFA.request(0, {
  1258. do: "story",
  1259. s: params.s
  1260. }, (s) => {
  1261. if (s) {
  1262. downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(s, null, 4)));
  1263. }
  1264. });
  1265. downloadLink.setAttribute('download', `${params.s}.json`);
  1266. downloadLink.appendChild(downloadButton);
  1267. document.querySelector('#savestory').parentNode.appendChild(newBr());
  1268. document.querySelector('#savestory').parentNode.appendChild(downloadLink);
  1269. }
  1270. }
  1271. else if (location.pathname === "/my/stories/pages/" && location.search) {
  1272. const adventureID = params.s;
  1273.  
  1274. const notifyLabel = createLabel('Notify readers of new pages during this editing session: ', 'notifyreaders');
  1275. const notifyButton = document.querySelector('#notifyreaders');
  1276. notifyButton.previousSibling.textContent = '';
  1277. notifyButton.parentNode.insertBefore(notifyLabel, notifyButton);/**/
  1278.  
  1279. if (!drafts[adventureID]) {
  1280. drafts[adventureID] = {};
  1281. saveDrafts(drafts);
  1282. }
  1283.  
  1284. pageLoad(() => {
  1285. if (document.querySelector('#storyname').textContent !== '-') {
  1286. drafts[adventureID].cachedTitle = document.querySelector('#storyname').textContent;
  1287. saveDrafts(drafts);
  1288. return true;
  1289. }
  1290. });
  1291.  
  1292. // Button links
  1293. addLink(document.querySelector('#editinfo'), `/my/stories/info/?s=${adventureID}`);
  1294.  
  1295. // Default spoiler values
  1296. const replaceButton = document.querySelector('#replaceall');
  1297. const spoilerButton = document.createElement('input');
  1298. Object.assign(spoilerButton, { className: 'major', value: 'Default Spoiler Values', type: 'button'});
  1299. replaceButton.parentNode.insertBefore(spoilerButton, replaceButton);
  1300. replaceButton.parentNode.insertBefore(newBr(), replaceButton);
  1301. replaceButton.parentNode.insertBefore(newBr(), replaceButton);
  1302.  
  1303. if (!settings.spoilerValues[adventureID]) {
  1304. settings.spoilerValues[adventureID] = {
  1305. open: 'Show',
  1306. close: 'Hide'
  1307. }
  1308. }
  1309.  
  1310. spoilerButton.addEventListener('click', evt => {
  1311. const spoilerSpan = document.createElement('span');
  1312. const spoilerOpen = document.createElement('input');
  1313. const spoilerClose = document.createElement('input');
  1314. spoilerSpan.appendChild(document.createTextNode('Open button text:'));
  1315. spoilerSpan.appendChild(newBr());
  1316. spoilerSpan.appendChild(spoilerOpen);
  1317. spoilerSpan.appendChild(newBr());
  1318. spoilerSpan.appendChild(newBr());
  1319. spoilerSpan.appendChild(document.createTextNode('Close button text:'));
  1320. spoilerSpan.appendChild(newBr());
  1321. spoilerSpan.appendChild(spoilerClose);
  1322.  
  1323. spoilerOpen.value = settings.spoilerValues[adventureID].open;
  1324. spoilerClose.value = settings.spoilerValues[adventureID].close;
  1325.  
  1326. window.MSPFA.dialog('Default Spoiler Values', spoilerSpan, ['Save', 'Cancel'], (output, form) => {
  1327. if (output === 'Save') {
  1328. settings.spoilerValues[adventureID].open = spoilerOpen.value === '' ? 'Show' : spoilerOpen.value;
  1329. settings.spoilerValues[adventureID].close = spoilerClose.value === '' ? 'Hide' : spoilerClose.value;
  1330. if (settings.spoilerValues[adventureID].open === 'Show' && settings.spoilerValues[adventureID].close === 'Hide') {
  1331. delete settings.spoilerValues[adventureID];
  1332. }
  1333. saveData(settings);
  1334. }
  1335. });
  1336. });
  1337.  
  1338. document.querySelector('input[title="Spoiler"]').addEventListener('click', evt => {
  1339. document.querySelector('#dialog input[name="open"]').value = document.querySelector('#dialog input[name="open"]').placeholder = settings.spoilerValues[adventureID].open;
  1340. document.querySelector('#dialog input[name="close"]').value = document.querySelector('#dialog input[name="close"]').placeholder = settings.spoilerValues[adventureID].close;
  1341. });
  1342.  
  1343. // --- Custom BBToolbar buttons
  1344. // Buttonless spoilers
  1345. const flashButton = document.querySelector('input[title=Flash]');
  1346. const newSpoilerButton = document.createElement('input');
  1347. newSpoilerButton.setAttribute('data-tag', 'Buttonless Spoiler');
  1348. Object.assign(newSpoilerButton, { title: 'Buttonless Spoiler', type: 'button', style: 'background-position: -66px -88px;' });
  1349.  
  1350. newSpoilerButton.addEventListener('click', evt => {
  1351. const bbe = document.querySelector('#bbtoolbar').parentNode.querySelector('textarea');
  1352. if (bbe) {
  1353. bbe.focus();
  1354. const start = bbe.selectionStart;
  1355. const end = bbe.selectionEnd;
  1356. bbe.value = bbe.value.slice(0, start) + '<div class="spoiler"><div>' + bbe.value.slice(start, end) + '</div></div>' + bbe.value.slice(end);
  1357. bbe.selectionStart = start + 26;
  1358. bbe.selectionEnd = end + 26;
  1359. }
  1360. });
  1361.  
  1362. flashButton.parentNode.insertBefore(newSpoilerButton, flashButton);
  1363.  
  1364. // Audio button
  1365. const audioButton = document.createElement('input');
  1366. Object.assign(audioButton, { title: 'Audio Player', type: 'button', style: 'background-position: -22px -110px' });
  1367.  
  1368. audioButton.addEventListener('click', evt => {
  1369. const bbe = document.querySelector('#bbtoolbar').parentNode.querySelector('textarea');
  1370. if (bbe) {
  1371. const msg = window.MSPFA.parseBBCode('Audio URL:<br>');
  1372. const audioInput = document.createElement('input');
  1373. Object.assign(audioInput, { type: 'url', name: 'audio-url', required: true });
  1374.  
  1375. const autoplayButton = document.createElement('input');
  1376. autoplayButton.type = 'checkbox';
  1377. autoplayButton.id = 'autoplay';
  1378. autoplayButton.checked = true;
  1379.  
  1380. const loopButton = document.createElement('input');
  1381. loopButton.type = 'checkbox';
  1382. loopButton.id = 'loop';
  1383. loopButton.checked = true;
  1384.  
  1385. const controlsButton = document.createElement('input');
  1386. controlsButton.type = 'checkbox';
  1387. controlsButton.id = 'controls';
  1388.  
  1389. msg.appendChild(audioInput);
  1390. msg.appendChild(newBr());
  1391. msg.appendChild(createLabel('Autoplay: ', 'autoplay'));
  1392. msg.appendChild(autoplayButton);
  1393. msg.appendChild(newBr());
  1394. msg.appendChild(createLabel('Loop: ', 'loop'));
  1395. msg.appendChild(loopButton);
  1396. msg.appendChild(newBr());
  1397. msg.appendChild(createLabel('Show controls: ', 'controls'));
  1398. msg.appendChild(controlsButton);
  1399. msg.appendChild(newBr());
  1400.  
  1401. window.MSPFA.dialog("Audio Player", msg, ["Okay", "Cancel"], (output, form) => {
  1402. if (output == "Okay") {
  1403. bbe.focus();
  1404. const start = bbe.selectionStart;
  1405. const end = bbe.selectionEnd;
  1406. const properties = `"${autoplayButton.checked ? ' autoplay' : ''}${loopButton.checked ? ' loop' : ''}${controlsButton.checked ? ' controls' : ''}`;
  1407. bbe.value = bbe.value.slice(0, start) + '<audio src="' + audioInput.value + properties +'>' + bbe.value.slice(start);
  1408. bbe.selectionStart = start + properties.length + audioInput.value.length + 13;
  1409. bbe.selectionEnd = end + properties.length + audioInput.value.length + 13;
  1410. }
  1411.  
  1412. });
  1413.  
  1414. audioInput.select();
  1415. }
  1416. });
  1417.  
  1418. flashButton.insertAdjacentElement('afterEnd', audioButton);
  1419.  
  1420. // YouTube button
  1421. const youtubeButton = document.createElement('input');
  1422. Object.assign(youtubeButton, { title: 'YouTube Video', type: 'button', style: 'background-position: 0px -110px' });
  1423.  
  1424. youtubeButton.addEventListener('click', evt => {
  1425. const bbe = document.querySelector('#bbtoolbar').parentNode.querySelector('textarea');
  1426. if (bbe) {
  1427. const msg = window.MSPFA.parseBBCode('Video URL:<br>');
  1428. const videoUrl = document.createElement('input');
  1429. videoUrl.type = 'url';
  1430. videoUrl.name = 'youtube';
  1431. videoUrl.required = true;
  1432.  
  1433. const autoplayButton = document.createElement('input');
  1434. autoplayButton.type = 'checkbox';
  1435. autoplayButton.checked = true;
  1436. autoplayButton.id = 'autoplay';
  1437.  
  1438. const controlsButton = document.createElement('input');
  1439. controlsButton.type = 'checkbox';
  1440. controlsButton.checked = true;
  1441. controlsButton.id = 'controls';
  1442.  
  1443. const fullscreenButton = document.createElement('input');
  1444. fullscreenButton.type = 'checkbox';
  1445. fullscreenButton.checked = true;
  1446. fullscreenButton.id = 'fullscreen';
  1447.  
  1448. const widthInput = document.createElement('input');
  1449. Object.assign(widthInput, { type: 'number', required: true, value: 650, style: 'width: 5em' });
  1450.  
  1451. const heightInput = document.createElement('input');
  1452. Object.assign(heightInput, { type: 'number', required: true, value: 450, style: 'width: 5em' });
  1453.  
  1454. msg.appendChild(videoUrl);
  1455. msg.appendChild(newBr());
  1456. msg.appendChild(createLabel('Autoplay: ', 'autoplay'));
  1457. msg.appendChild(autoplayButton);
  1458. msg.appendChild(newBr());
  1459. msg.appendChild(createLabel('Show controls: ', 'controls'));
  1460. msg.appendChild(controlsButton);
  1461. msg.appendChild(newBr());
  1462. msg.appendChild(createLabel('Allow fullscreen: ', 'fullscreen'));
  1463. msg.appendChild(fullscreenButton);
  1464. msg.appendChild(newBr());
  1465. msg.appendChild(document.createTextNode('Embed size: '));
  1466. msg.appendChild(widthInput);
  1467. msg.appendChild(document.createTextNode('x'));
  1468. msg.appendChild(heightInput);
  1469.  
  1470. window.MSPFA.dialog("YouTube Embed", msg, ["Okay", "Cancel"], (output, form) => {
  1471. if (output == "Okay") {
  1472. let videoID = videoUrl.value.split('/');
  1473. videoID = videoID[videoID.length-1].replace('watch?v=', '').split('&')[0];
  1474.  
  1475. bbe.focus();
  1476. const start = bbe.selectionStart;
  1477. const end = bbe.selectionEnd;
  1478. const iframeContent = `<iframe width="${widthInput.value}" height="${heightInput.value}" src="https://www.youtube.com/embed/${videoID}?autoplay=${+autoplayButton.checked}&controls=${+controlsButton.checked}" frameborder="0" allow="accelerometer; ${autoplayButton.checked ? 'autoplay; ' : ''}encrypted-media;"${fullscreenButton.checked ? ' allowfullscreen' : ''}></iframe>`;
  1479. bbe.value = bbe.value.slice(0, start) + iframeContent + bbe.value.slice(start);
  1480. bbe.selectionStart = start + iframeContent + 13;
  1481. bbe.selectionEnd = end + iframeContent + 13;
  1482. }
  1483.  
  1484. });
  1485.  
  1486. videoUrl.select();
  1487. }
  1488. });
  1489.  
  1490. flashButton.insertAdjacentElement('afterEnd', youtubeButton);
  1491. flashButton.insertAdjacentText('afterEnd', ' ');
  1492.  
  1493. // Get preview link
  1494. const getPreviewLink = (form) => {
  1495. const page = parseInt(form.querySelector('a.major').textContent.replace('Page ', ''));
  1496. return "/preview/?s=" + params.s + "&p=" + page + "&d=" + encodeURIComponent(JSON.stringify({
  1497. p: page,
  1498. c: form.querySelector('input[name=cmd]').value,
  1499. b: form.querySelector('textarea[name=body]').value,
  1500. n: form.querySelector('input[name=next]').value,
  1501. k: !form.querySelector('input[name=usekeys]').checked
  1502. }));
  1503. }
  1504.  
  1505. // -- Drafts --
  1506. // Accessing draft text
  1507. const accessDraftsButton = document.createElement('input');
  1508. Object.assign(accessDraftsButton, { className: 'major', value: 'Saved Drafts', type: 'button' });
  1509. replaceButton.parentNode.insertBefore(accessDraftsButton, replaceButton);
  1510. accessDraftsButton.parentNode.insertBefore(newBr(), replaceButton);
  1511. accessDraftsButton.parentNode.insertBefore(newBr(), replaceButton);
  1512.  
  1513. accessDraftsButton.addEventListener('click', () => {
  1514. loadDrafts();
  1515.  
  1516. const draftDialog = window.MSPFA.parseBBCode('Use the textbox below to copy out the data and save to a file somewhere else, or click the download button below.\nYou can also paste in data to replace the current drafts to ones stored there.');
  1517. const draftInputTextarea = document.createElement('textarea');
  1518. draftInputTextarea.placeholder = 'Paste your draft data here';
  1519. draftInputTextarea.style = 'width: 100%; box-sizing: border-box; resize: vertical;';
  1520.  
  1521. const downloadLink = document.createElement('a');
  1522. downloadLink.textContent = 'Download drafts';
  1523. downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(drafts[adventureID], null, 4)));
  1524. downloadLink.setAttribute('download', `${adventureID}.json`);
  1525.  
  1526. draftInputTextarea.rows = 8;
  1527. draftDialog.appendChild(newBr());
  1528. draftDialog.appendChild(newBr());
  1529. draftDialog.appendChild(draftInputTextarea);
  1530. draftDialog.appendChild(newBr());
  1531. draftDialog.appendChild(newBr());
  1532. draftDialog.appendChild(downloadLink);
  1533. setTimeout(() => {
  1534. draftInputTextarea.focus();
  1535. draftInputTextarea.selectionStart = 0;
  1536. draftInputTextarea.selectionEnd = 0;
  1537. draftInputTextarea.scrollTop = 0;
  1538. }, 1);
  1539.  
  1540. draftInputTextarea.value = JSON.stringify(drafts[adventureID], null, 4);
  1541.  
  1542. window.MSPFA.dialog('Saved Drafts', draftDialog, ["Load Draft", "Cancel"], (output, form) => {
  1543. if (output === "Load Draft") {
  1544. if (draftInputTextarea.value === '') {
  1545. setTimeout(() => {
  1546. window.MSPFA.dialog('Saved Drafts', window.MSPFA.parseBBCode('Are you sure you want to delete this adventure\'s draft data?\nMake sure you have it saved somewhere!'), ["Delete", "Cancel"], (output, form) => {
  1547. if (output === "Delete") {
  1548. loadDrafts();
  1549. drafts[adventureID] = {};
  1550.  
  1551. if (settings.drafts && settings.drafts[adventureID]) {
  1552. delete settings.drafts[adventureID];
  1553. saveData(settings);
  1554. }
  1555.  
  1556. saveDrafts(drafts);
  1557. }
  1558. });
  1559. }, 1);
  1560. } else if (draftInputTextarea.value !== JSON.stringify(drafts[adventureID], null, 4)) {
  1561. setTimeout(() => {
  1562. window.MSPFA.dialog('Saved Drafts', window.MSPFA.parseBBCode('Are you sure you want to load this draft data?\nAll previous draft data for this adventure will be lost!'), ["Load", "Cancel"], (output, form) => {
  1563. if (output === "Load") {
  1564. let newData = {};
  1565. try { // Just in case the data given is invalid.
  1566. newData = JSON.parse(draftInputTextarea.value);
  1567. } catch (err) {
  1568. console.error(err);
  1569. setTimeout(() => {
  1570. window.MSPFA.dialog('Error', window.MSPFA.parseBBCode('The entered data is invalid.'), ["Okay"]);
  1571. }, 1);
  1572. return;
  1573. }
  1574.  
  1575. loadDrafts();
  1576. drafts[adventureID] = newData;
  1577. saveDrafts(drafts);
  1578. }
  1579. });
  1580. }, 1);
  1581. }
  1582. }
  1583. });
  1584. });
  1585.  
  1586. // Draft stuff
  1587. const showDraftDialog = (pageNum) => {
  1588. loadDrafts();
  1589.  
  1590. const msg = document.createElement('span');
  1591. msg.appendChild(document.createTextNode('Command:'));
  1592. msg.appendChild(document.createElement('br'));
  1593.  
  1594. const commandInput = document.createElement('input');
  1595. Object.assign(commandInput, { style: 'width: 100%; box-sizing: border-box;', readOnly: true, });
  1596.  
  1597. msg.appendChild(commandInput);
  1598. msg.appendChild(document.createElement('br'));
  1599. msg.appendChild(document.createElement('br'));
  1600.  
  1601. msg.appendChild(document.createTextNode('Body:'));
  1602.  
  1603. const bodyInput = document.createElement('textarea');
  1604. Object.assign(bodyInput, { style: 'width: 100%; box-sizing: border-box; resize: vertical;', readOnly: true, rows: 8 });
  1605.  
  1606. msg.appendChild(bodyInput);
  1607.  
  1608. const pageElement = document.querySelector(`#p${pageNum}`);
  1609.  
  1610. let shownMessage = msg;
  1611. let optionButtons = [];
  1612.  
  1613. const commandElement = pageElement.querySelector('input[name="cmd"]');
  1614. const pageContentElement = pageElement.querySelector('textarea[name="body"]');
  1615.  
  1616. if (typeof drafts[adventureID][pageNum] === "undefined") {
  1617. shownMessage = document.createTextNode('There is no draft saved for this page.');
  1618. optionButtons = ["Save New", "Close"];
  1619. } else {
  1620. commandInput.value = drafts[adventureID][pageNum].command;
  1621. bodyInput.textContent = drafts[adventureID][pageNum].pageContent;
  1622. optionButtons = ["Save New", "Load", "Delete", "Close"];
  1623. }
  1624.  
  1625. window.MSPFA.dialog(`Page ${pageNum} Draft`, shownMessage, optionButtons, (output, form) => {
  1626. if (output === "Save New") {
  1627. if (typeof drafts[adventureID][pageNum] === "undefined") {
  1628. loadDrafts();
  1629. drafts[adventureID][pageNum] = {
  1630. command: commandElement.value,
  1631. pageContent: pageContentElement.value
  1632. }
  1633. saveDrafts(drafts);
  1634. } else {
  1635. setTimeout(() => {
  1636. window.MSPFA.dialog('Overwrite current draft?', document.createTextNode('Doing this will overwrite your current draft with what is currently written in the page box. Are you sure?'), ["Yes", "No"], (output, form) => {
  1637. if (output === "Yes") {
  1638. loadDrafts();
  1639. drafts[adventureID][pageNum] = {
  1640. command: commandElement.value,
  1641. pageContent: pageContentElement.value
  1642. }
  1643. saveDrafts(drafts);
  1644. }
  1645. });
  1646. }, 1);
  1647. }
  1648. } else if (output === "Load") {
  1649. if (pageContentElement.value === '' && (commandElement.value === '' || commandElement.value === document.querySelector('#defaultcmd').value)) {
  1650. commandElement.value = drafts[adventureID][pageNum].command;
  1651. pageContentElement.value = drafts[adventureID][pageNum].pageContent;
  1652. pageElement.querySelector('input[value="Save"]').disabled = false;
  1653. } else {
  1654. setTimeout(() => {
  1655. window.MSPFA.dialog('Overwrite current page?', document.createTextNode('Doing this will overwrite the page\'s content with what is currently written in the draft. Are you sure?'), ["Yes", "No"], (output, form) => {
  1656. if (output === "Yes") {
  1657. commandElement.value = drafts[adventureID][pageNum].command;
  1658. pageContentElement.value = drafts[adventureID][pageNum].pageContent;
  1659. pageElement.querySelector('input[value="Save"]').disabled = false;
  1660. }
  1661. });
  1662. }, 1);
  1663. }
  1664. } else if (output === "Delete") {
  1665. setTimeout(() => {
  1666. window.MSPFA.dialog('Delete this draft?', document.createTextNode('This action is irreversable! Are you sure?'), ["Yes", "No"], (output, form) => {
  1667. if (output === "Yes") {
  1668. loadDrafts();
  1669. delete drafts[adventureID][pageNum];
  1670.  
  1671. if (settings.drafts && settings.drafts[adventureID] && settings.drafts[adventureID][pageNum]) {
  1672. delete settings.drafts[adventureID][pageNum];
  1673. saveData(settings);
  1674. }
  1675.  
  1676. saveDrafts(drafts);
  1677. }
  1678. });
  1679. }, 1);
  1680. }
  1681. });
  1682. }
  1683.  
  1684. const createDraftButton = (form) => {
  1685. const draftButton = document.createElement('input');
  1686. Object.assign(draftButton, { className: 'major draft', type: 'button', value: 'Draft' });
  1687. draftButton.addEventListener('click', () => {
  1688. showDraftDialog(form.id.replace('p', ''));
  1689. });
  1690. return draftButton;
  1691. }
  1692.  
  1693. pageLoad(() => {
  1694. let allPages = document.querySelectorAll('#storypages form:not(#newpage)');
  1695. if (allPages.length !== 0) {
  1696. allPages.forEach(form => {
  1697. const prevButton = form.querySelector('input[name="preview"]');
  1698. prevButton.parentNode.insertBefore(createDraftButton(form), prevButton);
  1699. prevButton.parentNode.insertBefore(document.createTextNode(' '), prevButton);
  1700.  
  1701. // Preview
  1702. const previewButton = form.querySelector('input[value=Preview]');
  1703. const previewLink = addLink(previewButton, getPreviewLink(form), '_blank');
  1704. previewButton.addEventListener('mousedown', () => {
  1705. previewLink.href = getPreviewLink(form);
  1706. });
  1707.  
  1708. // "Enable keyboard shortcuts" label
  1709. const shortcutCheck = form.querySelector('input[type="checkbox"]');
  1710. shortcutCheck.previousSibling.textContent = '';
  1711. shortcutCheck.id = `key-${form.id}`;
  1712. shortcutCheck.parentNode.insertBefore(createLabel('Enable keyboard shortcuts: ', shortcutCheck.id), shortcutCheck);
  1713. });
  1714. document.querySelector('input[value="Add"]').addEventListener('click', () => {
  1715. allPages = document.querySelectorAll('#storypages form:not(#newpage)');
  1716. const form = document.querySelector(`#p${allPages.length}`);
  1717. const prevButton = form.querySelector('input[name="preview"]');
  1718. prevButton.parentNode.insertBefore(createDraftButton(form), prevButton);
  1719. prevButton.parentNode.insertBefore(document.createTextNode(' '), prevButton);
  1720.  
  1721. // Preview link
  1722. const previewButton = form.querySelector('input[value=Preview]');
  1723. const previewLink = addLink(previewButton, getPreviewLink(form), '_blank');
  1724. previewButton.addEventListener('mousedown', () => {
  1725. previewLink.href = getPreviewLink(form);
  1726. });
  1727.  
  1728. // "Enable keyboard shortcuts" label
  1729. const shortcutCheck = form.querySelector('input[type="checkbox"]');
  1730. shortcutCheck.previousSibling.textContent = '';
  1731. shortcutCheck.id = `key-${form.id}`;
  1732. shortcutCheck.parentNode.insertBefore(createLabel('Enable keyboard shortcuts: ', shortcutCheck.id), shortcutCheck);
  1733. });
  1734. const newForm = document.querySelector('#newpage');
  1735. {
  1736. // "Enable keyboard shortcuts" label
  1737. const shortcutCheck = newForm.querySelector('input[type="checkbox"]');
  1738. shortcutCheck.previousSibling.textContent = '';
  1739. shortcutCheck.id = `key-${newForm.id}`;
  1740. shortcutCheck.parentNode.insertBefore(createLabel('Enable keyboard shortcuts: ', shortcutCheck.id), shortcutCheck);
  1741. }
  1742. const newPreviewButton = newForm.querySelector('input[value=Preview]');
  1743. const newPreviewLink = addLink(newPreviewButton, getPreviewLink(newForm), '_blank');
  1744. newPreviewButton.addEventListener('mousedown', () => {
  1745. newPreviewLink.href = getPreviewLink(newForm);
  1746. });
  1747. return true;
  1748. }
  1749. });
  1750.  
  1751. if (params.click) {
  1752. if (params.click === 's') {
  1753. spoilerButton.click();
  1754. } else if (params.click === 'd') {
  1755. accessDraftsButton.click();
  1756. }
  1757. }
  1758.  
  1759. // Don't scroll after pressing a BBToolbar button (awesome)
  1760. let lastScroll = window.scrollY;
  1761. pageLoad(() => {
  1762. if (document.querySelectorAll('#storypages textarea').length > 1) {
  1763. document.querySelectorAll('#storypages textarea').forEach(textarea => {
  1764. textarea.addEventListener('focus', () => {
  1765. window.scrollTo(window.scrollX, lastScroll);
  1766. });
  1767. });
  1768.  
  1769. document.addEventListener('scroll', evt => {
  1770. lastScroll = window.scrollY;
  1771. });
  1772. return true;
  1773. }
  1774. });
  1775.  
  1776. // Focus on the text input when clicking on the Color or Background Color BBToolbar buttons
  1777. const colourButtons = [document.querySelector('#bbtoolbar input[data-tag=color]'), document.querySelector('#bbtoolbar input[data-tag=background]')];
  1778. colourButtons.forEach(button => {
  1779. button.addEventListener('click', () => {
  1780. document.querySelector('#dialog input[type=text]').select();
  1781. });
  1782. });
  1783. }
  1784. else if (location.pathname === "/my/profile/") {
  1785. // Nothing
  1786. }
  1787. else if (location.pathname === "/user/") {
  1788. // Button links
  1789. pageLoad(() => {
  1790. const msgButton = document.querySelector('#sendmsg');
  1791. if (msgButton) {
  1792. addLink(msgButton, `/my/messages/new/?u=${params.u}`);
  1793. addLink(document.querySelector('#favstories'), `/favs/?u=${params.u}`);
  1794. return true;
  1795. }
  1796. });
  1797.  
  1798. // Add extra user stats
  1799. pageLoad(() => {
  1800. if (window.MSPFA) {
  1801. const stats = document.querySelector('#userinfo table');
  1802.  
  1803. const joinTr = stats.insertRow(1);
  1804. const joinTextTd = joinTr.insertCell(0);
  1805. joinTextTd.appendChild(document.createTextNode("Account created:"));
  1806. const joinDate = joinTr.insertCell(1);
  1807. const joinTime = document.createElement('b');
  1808. joinTime.textContent = "Loading...";
  1809. joinDate.appendChild(joinTime);
  1810.  
  1811. const advCountTr = stats.insertRow(2);
  1812. const advTextTd = advCountTr.insertCell(0);
  1813. advTextTd.appendChild(document.createTextNode("Adventures created:"));
  1814. const advCount = advCountTr.insertCell(1);
  1815. const advCountText = document.createElement('b');
  1816. advCountText.textContent = "Loading...";
  1817. advCount.appendChild(advCountText);
  1818.  
  1819. // Show user creation date
  1820. window.MSPFA.request(0, {
  1821. do: "user",
  1822. u: params.u
  1823. }, user => {
  1824. if (typeof user !== "undefined") {
  1825. joinTime.textContent = new Date(user.d).toString().split(' ').splice(1, 4).join(' ');
  1826. }
  1827.  
  1828. // Show created adventures
  1829. window.MSPFA.request(0, {
  1830. do: "editor",
  1831. u: params.u
  1832. }, s => {
  1833. if (typeof s !== "undefined") {
  1834. advCountText.textContent = s.length;
  1835. }
  1836.  
  1837. // Show favourites
  1838. if (document.querySelector('#favstories').style.display !== 'none') {
  1839. const favCountTr = stats.insertRow(3);
  1840. const favTextTd = favCountTr.insertCell(0);
  1841. favTextTd.appendChild(document.createTextNode("Adventures favorited:"));
  1842. const favCount = favCountTr.insertCell(1);
  1843. const favCountText = document.createElement('b');
  1844. favCountText.textContent = "Loading...";
  1845. window.MSPFA.request(0, {
  1846. do: "favs",
  1847. u: params.u
  1848. }, s => {
  1849. if (typeof s !== "undefined") {
  1850. favCountText.textContent = s.length;
  1851. }
  1852. });
  1853. favCount.appendChild(favCountText);
  1854. }
  1855. });
  1856. });
  1857.  
  1858. return true;
  1859. }
  1860. });
  1861. }
  1862. else if (location.pathname === "/favs/" && location.search) {
  1863. const toggleButton = document.createElement('input');
  1864. Object.assign(toggleButton, { className: "major", type: "button", value: "Toggle Muted Adventures" });
  1865. const buttonRow = document.querySelector('table.container.alt').insertRow(2);
  1866. const actionSpan = document.createElement('span');
  1867.  
  1868. let stories = [];
  1869. // Button links
  1870. pageLoad(() => {
  1871. stories = document.querySelectorAll('#stories tr');
  1872. let favCount = 0;
  1873.  
  1874. if (stories.length > 0) {
  1875. stories.forEach(story => {
  1876. favCount++;
  1877. const id = story.querySelector('a').href.replace('https://mspfa.com/', '');
  1878. pageLoad(() => {
  1879. if (window.MSPFA.me.i) {
  1880. addLink(story.querySelector('.edit.major'), `/my/stories/info/${id}`);
  1881. return true;
  1882. }
  1883. if (pageLoaded) return true;
  1884. });
  1885. addLink(story.querySelector('.rss.major'), `/rss/${id}`);
  1886. });
  1887.  
  1888. // Fav count
  1889. const username = document.querySelector('#username');
  1890. username.parentNode.appendChild(newBr());
  1891. username.parentNode.appendChild(newBr());
  1892. username.parentNode.appendChild(document.createTextNode(`Favorited adventures: ${favCount}`));
  1893.  
  1894. return true;
  1895. }
  1896. if (pageLoaded) return true;
  1897. });
  1898.  
  1899. pageLoad(() => {
  1900. if (window.MSPFA && window.MSPFA.me) {
  1901. if (window.MSPFA.me.i === params.u) {
  1902. const cell = buttonRow.insertCell(0);
  1903. cell.appendChild(toggleButton);
  1904. cell.appendChild(newBr());
  1905. cell.appendChild(actionSpan);
  1906. return true;
  1907. }
  1908. }
  1909. if (pageLoaded) return true;
  1910. });
  1911.  
  1912. let type = 0;
  1913.  
  1914. toggleButton.addEventListener('click', () => {
  1915. type++;
  1916. if (type > 2) type = 0;
  1917.  
  1918. stories.forEach(story => {
  1919. const unmuted = story.querySelector('.notify').className.includes(' lit');
  1920. story.style.display = '';
  1921. if (type === 2 && unmuted || type === 1 && !unmuted) {
  1922. story.style.display = 'none';
  1923. }
  1924. });
  1925.  
  1926. if (type === 0) {
  1927. // show all
  1928. actionSpan.textContent = '';
  1929. }
  1930. else if (type === 1) {
  1931. // hide muted
  1932. actionSpan.textContent = 'Showing only unmuted favourites';
  1933. }
  1934. else {
  1935. // only muted
  1936. actionSpan.textContent = 'Showing only muted favourites';
  1937. }
  1938. });
  1939. }
  1940. else if (location.pathname === "/search/" && location.search) {
  1941. // Character and word statistics
  1942. const statTable = document.createElement('table');
  1943. const statTbody = document.createElement('tbody');
  1944. const statTr = statTbody.insertRow(0);
  1945. const charCount = statTr.insertCell(0);
  1946. const wordCount = statTr.insertCell(0);
  1947. const statParentTr = document.querySelector('#pages').parentNode.parentNode.insertRow(2);
  1948. const statParentTd = statParentTr.insertCell(0);
  1949.  
  1950. const statHeaderTr = statTbody.insertRow(0);
  1951. const statHeader = document.createElement('th');
  1952. statHeader.colSpan = '2';
  1953.  
  1954. statHeaderTr.appendChild(statHeader);
  1955. statHeader.textContent = 'Statistics may not be entirely accurate.';
  1956.  
  1957. statTable.style.width = "100%";
  1958.  
  1959. charCount.textContent = "Character count: loading...";
  1960. wordCount.textContent = "Word count: loading...";
  1961.  
  1962. statTable.appendChild(statTbody);
  1963. statParentTd.appendChild(statTable);
  1964.  
  1965. pageLoad(() => {
  1966. if (document.querySelector('#pages br')) {
  1967. const bbc = window.MSPFA.BBC.slice();
  1968. bbc.splice(0, 3);
  1969.  
  1970. window.MSPFA.request(0, {
  1971. do: "story",
  1972. s: params.s
  1973. }, story => {
  1974. if (typeof story !== "undefined") {
  1975. const pageContent = [];
  1976. story.p.forEach(p => {
  1977. pageContent.push(p.c);
  1978. pageContent.push(p.b);
  1979. });
  1980.  
  1981. const storyText = pageContent.join(' ')
  1982. .replace(/\n/g, ' ')
  1983. .replace(bbc[0][0], '$1')
  1984. .replace(bbc[1][0], '$1')
  1985. .replace(bbc[2][0], '$1')
  1986. .replace(bbc[3][0], '$1')
  1987. .replace(bbc[4][0], '$2')
  1988. .replace(bbc[5][0], '$3')
  1989. .replace(bbc[6][0], '$3')
  1990. .replace(bbc[7][0], '$3')
  1991. .replace(bbc[8][0], '$3')
  1992. .replace(bbc[9][0], '$3')
  1993. .replace(bbc[10][0], '$2')
  1994. .replace(bbc[11][0], '$1')
  1995. .replace(bbc[12][0], '$3')
  1996. .replace(bbc[13][0], '$3')
  1997. .replace(bbc[14][0], '')
  1998. .replace(bbc[16][0], '$1')
  1999. .replace(bbc[17][0], '$2 $4 $5')
  2000. .replace(bbc[18][0], '$2 $4 $5')
  2001. .replace(bbc[19][0], '')
  2002. .replace(bbc[20][0], '')
  2003. .replace(/<(.*?)>/g, '');
  2004.  
  2005. wordCount.textContent = `Word count: ${storyText.split(/ +/g).length}`;
  2006. charCount.textContent = `Character count: ${storyText.replace(/ +/g, '').length}`;
  2007. }
  2008. });
  2009. return true;
  2010. }
  2011. });
  2012. }
  2013. else if (location.pathname === "/stories/" && location.search) {
  2014. // Click text to check/uncheck boxes
  2015. ['Ongoing', 'Complete', 'Inactive'].forEach(t => {
  2016. const check = document.querySelector(`input[name="${t.toLowerCase()}"]`);
  2017. check.id = `check_${t.toLowerCase()}`;
  2018. const label = createLabel(' ' + t + ' ', check.id);
  2019. check.nextSibling.textContent = '';
  2020. check.parentNode.insertBefore(label, check.nextSibling);
  2021. });
  2022.  
  2023. const adventureList = document.querySelector('#doit');
  2024. const resultAmount = document.createElement('span');
  2025. adventureList.parentNode.appendChild(resultAmount);
  2026.  
  2027. pageLoad(() => {
  2028. if (window.MSPFA) {
  2029. window.MSPFA.request(0, {
  2030. do: "stories",
  2031. n: params.n,
  2032. t: params.t,
  2033. h: params.h,
  2034. o: params.o,
  2035. p: params.p,
  2036. m: 20000
  2037. }, (s) => {
  2038. resultAmount.textContent = `Number of results: ${s.length}`;
  2039. return true;
  2040. });
  2041. return true;
  2042. }
  2043. },1);
  2044.  
  2045. pageLoad(() => {
  2046. const stories = document.querySelector('#stories');
  2047. if (stories.childNodes.length > 0) {
  2048. if (params.load && stories.childNodes.length === 1) {
  2049. stories.querySelector('a').click();
  2050. }
  2051.  
  2052. stories.querySelectorAll('tr').forEach(story => {
  2053. const storyID = story.querySelector('a.major').href.split('&')[0].replace(/\D/g, '');
  2054. addLink(story.querySelector('.rss'), `/rss/?s=${storyID}`);
  2055.  
  2056. pageLoad(() => {
  2057. if (window.MSPFA.me.i) {
  2058. addLink(story.querySelector('.edit.major'), `/my/stories/info/?s=${storyID}`);
  2059. return true;
  2060. }
  2061. if (pageLoaded) return true;
  2062. });
  2063. });
  2064. return true;
  2065. }
  2066. if (pageLoaded) return true;
  2067. });
  2068. }
  2069. })();