MSPFA extras

Adds custom quality of life features to MSPFA.

当前为 2020-09-18 提交的版本,查看 最新版本

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