Styx / FFN Tweaks

// ==UserScript==
// @name         FFN Tweaks
// @version      0.0.2
// @namespace    https://fanfics.me/user159153
// @description  Useful features for fanfiction.net
// @author       Styx
// @copyright    2019, Styx (https://fanfics.me/user159153)
// @license      MIT; https://opensource.org/licenses/MIT
// @homepageURL  https://fanfics.me/index.php?section=blogs&search=%23ffn_tweaks
// @supportURL   https://fanfics.me/index.php?section=blogs&search=%23ffn_tweaks
// @updateURL    https://openuserjs.org/meta/Styx/FFN_Tweaks.meta.js
// @include      https://www.fanfiction.net/*
// @run-at       document-idle
// @grant        none
// ==/UserScript==

/**
 Copyright 2019 Styx (https://fanfics.me/user159153)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * RELEASE NOTES:
 *
 * 0.0.2
 *   + Добавлен режим чтения "все главы на одной странице"
 *
 * 0.0.1
 *   + Включает возможность выделять текст
 */

(function () {
  'use strict';

  let inRead = false;
  let sid = -1;
  let cid = -1;
  let st = '';
  const m = self.location.pathname.match(/^\/s\/(\d+)(?:\/(\d+)(?:\/([^/]+))?)?/);
  if (m != null) {
    sid = parseInt(m[1], 10) || -1;
    cid = parseInt(m[2], 10);
    st = m[3] || '';
    inRead = ~sid;
  }
  const inAllChapters = cid === 0;

  if (!inRead) {
    return;
  }

  const CSS =
    `
  h3.ffnt-ch-ttl { text-align: center; color: #333399; }
  hr.ffnt-ch-sep { height: 4px; margin: 30px 0; background-image: -webkit-gradient(linear,left bottom,right bottom,color-stop(0,#fff),color-stop(0.1,#333399),color-stop(0.9,#333399),color-stop(1,#fff)); }
  .ffnt-sel-cont { display: flex; justify-content: space-between; }
  .ffnt-sel-cont > span { display: block; float: none !important; }
  .ffnt-sel-map {  position: fixed; z-index: 9999; right: 0; top: calc(100% / 4); transition: transform 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55); transform: translateX(100%); }
  .ffnt-sel-map.ffnt-show { transform: none; }
  .ffnt-sel-map > button { position: absolute; top: 0; right: 100%; margin-right: -1px; outline: none; font-size: 26px; line-height: 39px; padding: 3px 6px 0; }
  .ffnt-sel-map > select { border-radius: 0; max-height: calc(50vh); overflow-y: scroll; }
  .ffnt-pgs-bar { position: fixed; z-index: 9999; top: 0; left: 0; height: 3px; width: 1%; background-color: #c2185b; box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5); }
`;

  const story = document.querySelector('#storytext');

  const chapterTitle = withClass(document.createElement('h3'), 'ffnt-ch-ttl');
  const chapterSeparator = withClass(document.createElement('hr'), 'ffnt-ch-sep');

  injectCSS();
  enableTextSelection();
  fixChapterSelector();
  loadAllChapters();

  function injectCSS() {
    const style = document.createElement('style');
    style.textContent = CSS;
    document.querySelector('head').appendChild(style);
  }

  function withClass(el, cls) {
    cls.split(' ').forEach(c => el.classList.add(c));
    return el;
  }

  function applyStyles(el, styles) {
    Object.keys(styles).forEach(k => (el.style[k] = styles[k]));
    return el;
  }

  function fixChapterSelector() {
    const select = document.querySelector('span > #chap_select');
    if (select == null) {
      return;
    }
    const p = select.parentNode;
    const div = withClass(document.createElement('div'), 'ffnt-sel-cont');
    p.parentElement.insertBefore(div, p);
    if (!inAllChapters) {
      const btn = withClass(document.createElement('button'), 'btn');
      btn.type = 'button';
      btn.addEventListener('click', function () {
        self.location = `/s/${sid}/0/${st}`;
      });
      btn.textContent = 'All Chapters';
      div.appendChild(btn);
    }
    div.appendChild(p);
  }

  function addChapterTitle(item, first = false) {
    const ttl = chapterTitle.cloneNode();
    ttl.textContent = item.txt;
    ttl.id = `ffnt-chapter-${item.cid}`;
    if (!first) {
      story.appendChild(chapterSeparator.cloneNode());
    }
    story.insertBefore(ttl, !!first ? story.firstChild : null);
  }

  function loadAllChapters() {
    if (cid !== 0) {
      return;
    }
    const select = document.querySelector('span > #chap_select');
    if (select == null) {
      return;
    }

    const _select = document.querySelector('div > #chap_select').parentNode;
    _select.parentNode.removeChild(_select);

    const progressBar = withClass(document.createElement('div'), 'ffnt-pgs-bar');
    story.parentNode.insertBefore(progressBar, story);

    const lst = Array.from(select.querySelectorAll('option'))
      .map(e => ({ cid: e.value, txt: e.textContent.trim() }))
      .sort((a, b) => a.cid - b.cid);

    const first = lst.shift();
    addChapterTitle(first, true);

    const progress = (() => {
      const diff = Math.ceil(100.0 / lst.length);
      let cnt = 0;
      return () => {
        setTimeout(() => {
          cnt = Math.min(cnt + diff, 100);
          progressBar.style.width = `${cnt}%`;
        }, 1);
      };
    })();

    const storyTitle = document.querySelector('#profile_top b');
    const storyLink = document.createElement('a');
    storyLink.href = `/s/${sid}/1/${st}`;
    storyTitle.parentNode.insertBefore(storyLink, storyTitle);
    storyLink.appendChild(storyTitle);

    const map = select.parentElement;
    withClass(map, 'ffnt-sel-map ffnt-show');
    select.size = lst.length + 1;
    select.setAttribute('onchange', 'self.location = "#ffnt-chapter-" + this.options[this.selectedIndex].value');

    const mapShow = map.querySelector('button');
    mapShow.classList.remove('btn');
    mapShow.innerHTML = '🗺'
    mapShow.removeAttribute('onclick');
    mapShow.addEventListener('click', () => {
      map.classList.toggle('ffnt-show');
    });

    lst.reduce((p, item) => {
      return p.then(() => {
        return fetch(`/s/${sid}/${item.cid}/${st}`)
          .then(res => res.text())
          .then(text => {
            text = text.substr(text.search(/<div[^>]+?['"]storytext["']/));
            text = text.substr(0, text.search(/<\/div/) + 6);
            let div = document.createElement('div');
            div.innerHTML = text;
            text = null;
            addChapterTitle(item);
            div.querySelector('#storytext').childNodes.forEach(c => story.appendChild(c));
            div = null;
            progress();
            return new Promise(resolve => setTimeout(resolve, 50));
          });
      });
    }, Promise.resolve()).then(() => {
      progressBar.parentNode.removeChild(progressBar);
      map.classList.remove('ffnt-show');
    });
  }

  function enableTextSelection() {
    setTimeout(function () {
      // enable text selection
      const re = /select/i;
      let el = document.querySelector('#storytextp');
      if (el != null) {
        Array.from(window.getComputedStyle(el))
          .filter(s => re.test(s))
          .forEach(s => {
            el.style[s] = '';
          });
      }
    }, 500);
  }

})();